Beruflich Dokumente
Kultur Dokumente
>> To day in IT Sector we have three types of s/w applications, they are
>> To day in the IT Sector the developers or programmers can develop two types
of applications they are
1) Standalone Applications
2) Distributed Applications
The applications which is going to run under the context of a local system hard
disk and whose results are not sharable across the globe, those are come under
standalone applications.
The applications which is going to run under the context of a server hard disk (we
are going to access them via client browser) and these results are sharable across the
globe, those are come under the category of Distributed applications.
Software Engineering:
Product: The developed s/w application is common for all the clients are
known as products.
Project: The developed s/w application is not common for the clients and
it is different for the different clients based on their requirement are known as
project.
EG: Some of the Project based companies are TCS, WIPRO, and INFOSYS...Etc…
urtrainer.java@gmail.com
Java Fundamentals JAVA CSREDDY
Feasibility:
Normalization Use:
NORMALIZATION is used for the process of breaking up the data into several
tables so as to minimize the number of times we have to repeat the same data.
urtrainer.java@gmail.com
Java Fundamentals JAVA CSREDDY
And JAVA is divided into 3 categories. They are J2SE, J2EE, and J2ME.
>J2SE (Java2 Standard Edition) is used for developing client side applications.
>J2EE (Java2 Enterprise Edition) is used for developing server side applications.
urtrainer.java@gmail.com
Java Fundamentals JAVA CSREDDY
1) Simple
2) Platform Independent
3) Architectural Neutral
4) Portable
5) Multi Threaded
6) Networked
7) Distributed
8) High Performance
9) Interpreted
10) Robust
11) Dynamic
12) Secured
13) Object Oriented Programming Language
Simple:
1) Java is one of the simple programming languages why because java is totally
free from pointers. So 60% of the complexity is reduced.
2) Java Programming environment is free from pointers, i.e. the concept of
pointers cannot be used in java programming. Hence we get faster
development and faster execution of the java program. [ Byte code is so
faster than ordinary pointer code];
3) Java programming environment contains in built garbage collector for
collecting unused memory locations for improving the performance.
4) Java Programming environment can contain rich set of API [Application
Programming interface]. API it is a collection of packages. And package is a
collection of classes and interfaces and they interns contains collection of
predefined functions.
urtrainer.java@gmail.com
Java Fundamentals JAVA CSREDDY
5) Java Programming environment contains user friendly syntaxes for
developing effective applications in java.
1. The languages like c/c++ are treated as platform dependent since the data
types of c/c++ varying the memory space from one operating system to
another operating system.
2. The s/w of c/c++ is unable to convert one format of one operating system to
another format of other operating systems. [ DOS understands everything in
the format of MOZARTA (MZ) where as UNIX understands everything in
Embedded Linking Format (elf)]
3. The languages like java is treated as Platform independent since the data
types of java takes same memory space on all available operating systems.
4. The java s/w contains some special programs to convert from one format of
one operating system to other format of other operating system.
5. Finally the SLOGAN of Sun Micro Systems is “Writing once Run / Reuse
Anywhere” [WORA].
Architectural Neutral:
urtrainer.java@gmail.com
Java Fundamentals JAVA CSREDDY
3. The languages like java is treated as architecture neutral language since the
s/w of java contains some special programs to convert some factors of one
processor to some other factors of another processor.
Portable:
A portable language is one which will run on every operating system and every
processor without considering their vendors and architectures.
The languages like c/c++ are treated as non portable languages. The language java
is treated as portable language.
Multi Threading:
If a java program contains multiple flow of controls (Threads) then that java
program is known as Multi threading program.
The purpose of thread is to execute the specific operation.
The basic aim of multi threading is to achieve concurrent or simultaneous
execution.
The real time implementation of multi threading is that server development.
Multi Threading is a specialized form of multi tasking when we write any
program in java environment it contains 2 Threads. They are Fore Ground
Thread and Back Ground thread.
Fore Ground thread is one which always executes user defined methods and
there is a possibility of creating multiple fore ground threads.
A Back Ground thread is one which always monitors the status of fore ground
thread.
urtrainer.java@gmail.com
Java Fundamentals JAVA CSREDDY
> Along with the regular java program there exists one of the back ground
program called Garbage Collector for monitoring the status of the regular java
program.
The thread which is created to execute regular java program is known as fore
ground thread and garbage collector is treated as back ground thread. Hence in
our java program 2 threads are running.
Networked:
The basic aim of networking is that to share the data between multiple
machines either locally or globally.
1. Un Trusted Network
2. Trusted Network
Untrusted Network is one in which there exists collection of inter
connected Non- Autonomous computers. Using this network architecture we
can develop Intranet Applications by using J2SE.
Distributed:
JAVA
2) Distributed application
Distributed application is one which runs in multiple servers they can be developed
by using j2EE technologies. The advantage of Distributed application is that more
availability of data.
High- Performance:
The magic of Byte Code will make the program execution faster.
Interpreted:
Robust:
urtrainer.java@gmail.com
Java Fundamentals JAVA CSREDDY
Secured:
Dynamic:
Disadvantages:
Java does not fallow static memory allocation due to above problems. But java
always follows Dynamic Memory Allocation only.
1) Programming Language
2) Translator
3) Storage Areas
urtrainer.java@gmail.com
Java Fundamentals JAVA CSREDDY
4) Data Types
5) Tokens
6) Programming Constructs
Translator: Translator is nothing but a software program which can translate High
level language representation of source program into Machine level language
representations and Machine level language representations into human readable
format i.e. high level language representations.
Storage Areas:
File Systems:
Databases:
Data Warehouses:
urtrainer.java@gmail.com
Java Fundamentals JAVA CSREDDY
Data Types:
Data types are basically used to represent the input of the program in the
main memory of the computer by allocating sufficient memory space. In general in
any programming language we have 3 types of data types. They are
These category data types are used for representing integer data. The
following table gives the types of integer category data types.
0 to 255
0 to 255/2
127.5 => 127.5
-0.5 +0.5
127 -128
Float category Data Types are used for representing float values which are in the
form of scale, precision.
Ex: 500.789
Scale precision
The following table gives the types of float category data types.
Whenever we represent a real constant value using a float data type, the real
constant must be followed by a letter f otherwise; it will be treated as highest data
type in float category i.e. double.
To represent character data in java we use a data type called “char”. This type
takes 2 bytes since java follows Unicode character set and it is available in 18
international languages.
UNICODE character set: It is one which contains all the characters which are
available in 18 international languages and it is followed by those programming
languages which are available in more than one international language.
NOTE:
Boolean category Data Type is used for representing logical values (true/false). To
represent true/false we use boolean data type. This data type takes 0 bytes why
because instead of storing the value in RAM it is stored in Flip Flops.
urtrainer.java@gmail.com
Java Fundamentals JAVA CSREDDY
And it is only one bit.
Note:
Derived Data Types are those whose variables allow us to represent multiple
values of the same data type but they are unable to represent multiple values of
different type.
Example: arrays
Tokens:
Keywords
Identifiers
Constants
Strings
Special Symbols
urtrainer.java@gmail.com
Java Fundamentals JAVA CSREDDY
Operators
urtrainer.java@gmail.com
Java Fundamentals JAVA CSREDDY
Note: Remaining like operators and special symbols I hope you all aware about
that.
Programming Constructs:
Programming Constructs are again categorized into 3 types and they are
Comments in java:
Comments of any programming language improve readability/ Understandability /
Clarity. Java contains 3 types of comments;
urtrainer.java@gmail.com
Java Fundamentals JAVA CSREDDY
*/
Variables in Java:
Whenever we pass any values to the java program, those values must be
presented interms of variables. Hence variables are treated as Building Blocks of
programming language.
Declaration of a Variable:
It is nothing but allocating sufficient amount of memory space for the variables.
Before using any variables in java, they must be declared.
Syntax:
data type represents either fundamental data type/ derived/ user defined data
type.
Eg: int x; float f1, f2; boolean b; Here we are getting default values for the
variables.
It is nothing but allocating memory space for the variables and placing our
own values without placing default values.
Syntax:
urtrainer.java@gmail.com
Java Fundamentals JAVA CSREDDY
val1,val2,…,valn represents corresponding values for v1,v2,…vn.
Constants in java:
A constant is an identifier whose value can not be changed during execution of the
program. In order to make anything as constant in Java we use a keyword called
‘final’. Final keyword is placing an important role in 3 places. They are
1) At Variable Level
2) At Method Level
3) At Class Level
At Variable Level:
If we don’t want to change the value of the variable then that variable must be
made as final.
Syntax:
At Method Level:
Each and every operation in java can be performed with respect to method.
If we don’t want to change the definition of the method, then that method must
be made as final.
Syntax:
urtrainer.java@gmail.com
Java Fundamentals JAVA CSREDDY
{ //block of statement(s);
Ex:
return (res);
At Class Level:
If we don’t want to give the features of base class to the derived class, then the base
class must be made as final
Syntax:
final class <ClassName>
{
//Body of the class
}
Final classes cannot be inherited by derived classes i.e. final classes will not participate
in Inheritance process.
Object oriented Programming Concepts:
1) Class
2) Object
4) Data Encapsulation
5) Inheritance
6) Polymorpisham
urtrainer.java@gmail.com
Java Fundamentals JAVA CSREDDY
7) Dynamic Binding
8) Message Passing
Classes:
1) The purpose of class is to develop user defined data types.
2) Each and every java program must be developed by using the concept called
classes.
A class is a way of binding the data members and associated methods in a single
unit.
a) The data members of the class are also known as properties or attributes where as
methods of the class are also known as behaviors or accessories.
b) In object oriented programming we have 2 types of methods. They are 1) Member
Methods 2) Non-Member Methods
c) A Member Method is one which is available within the scope of the class and they
can access private data of the class.
d) A Non_Member Method is one which does not come under the scope of the class
and they cannot access private data of the class.
e) In java programming environment member methods are allowed, but there is no
concept of Non-Member methods. Hence java provides 100% security.
Syntax:
class <ClassName>
urtrainer.java@gmail.com
Java Fundamentals JAVA CSREDDY
Each and every operation in java must be performed with respect to methods.
Each and every method of java must be defined with in class and such methods
are known as member methods.
Objects:
Whenever we create a class there is no memory space for data members and
methods of a class and memory space will be coming when we create an object.
Definitions:
Instance of a class is known as object.
Instance is nothing but allocating sufficient memory space for data members and
methods of a class.
Class variable is known as an object.
Grouped item is known as an object.
(If a variable contains multiple values of same type or different type or both then
that item is known as grouped item)
Value form of a class is known as an object.
Blue print of a class is known as an object.
Real world entities are known as an object.
Creation of Object:
urtrainer.java@gmail.com
Java Fundamentals JAVA CSREDDY
Syntax2:
<ClassName> objectname; // represents object declaration and whose default
value is null.
objectname=new <ClassName(); // represents object referencing and whose
default value is not null.
Types of Data members/Variables in Java:
In java programming environment every program must be written with respect to
classes. In Java the class can contain 2 types of data members, they are
1) Instance or Non Static Variables
2) Static Data Members
SNO Instance Data Members Static Data Members
1 Instance Data Members are those Static Data Members are those whose
whose memory space is created memory is created only once when the class
each and every time when an is loaded in main memory irrespective of
object is created. number of objects created.
2 Programmatically instance variables Programmatically static variables declaration
declaration should not be preceded must be preceded by a keyword called
by a key word ‘static’ “static”
3 Syntax: Syntax:
Data type v1,v2,….,vn; Static data type v1,v2,..,vn;
4 Instance Data Members are Static Data Members must be accessed with
accessed with respect to object respect to class name.
name. Classname.staticmembername;
Obj.instancemembername;
5 The value of instance data member The value of static data member is always
is not sharable sharable
6 Instance Data Members are also Static Data Members are also known as class
known as object level data level data members since they depends on
members since they depends on class and independent from object.
object and independent from class. Ex:
Ex: int stno; static String ename;
urtrainer.java@gmail.com
Java Fundamentals JAVA CSREDDY
Note: The classes are loaded into main memory with the help of Class Loader Sub
System (Which is a part of JVM).
urtrainer.java@gmail.com
Java Fundamentals JAVA CSREDDY
as object level methods since they methods since they depends on class and
depend on object and independent independent from object.
from class.
Example:
System.out.println ();
The above statement is used for displaying the data on the console Line By Line
System.out.print();
The above statement is used for displaying the data on the console in the same line.
println () and print () methods are the 2 predefined instance methods present in
one of the predefined class called PrintStream. To access print() and println() methods
we need an object of PrintStream class.
An object of PrintStream class called “out” is created as a static data member in
another predefined class System. Hence print(), println() methods must be accessed by
us in the java programming as follows.
System.out.println ();
System.out.println ();
Hungarian Notation:
This is the naming convention followed by Sun Microsystems for development of Library
/ API of JAVA.
Rule for Class/ Interface:
If a class name contains either one or more than one word then all the words first letters
must be capital.
Ex: system Normal Notation System Hungarian Notation
printstream PrintStream
numberformatexception NumberFormatException
arrayindexoutofboundsexception ArrayIndexOutOfBoundsException
Rule for Method:
If a method name contains either one or more than one word, then first word first letter
is small and rest of the subsequent words first letters must be capital.
urtrainer.java@gmail.com
Java Fundamentals JAVA CSREDDY
Normal Notation Hungarian Notation
println (); println ();
actionperformed(); actionPerformed();
adjustmentvaluechanged (); adjustmentvaluechanged();
class Command
{ public static void main(String args[])
{ System.out.println("No of Values="+args.length);
int x=Integer.parseInt(args[0]);
int y=Integer.parseInt(args[1]);
float n1=Float.parseFloat(args[2]);
float n2=Float.parseFloat(args[3]);
urtrainer.java@gmail.com
Java Fundamentals JAVA CSREDDY
int z=x+y;
float n3=n1+n2;
System.out.println(z);
System.out.println(n3);
}
}
// Display all command-line arguments.
class CommandLine
{ public static void main(String args[])
{ System.out.println("Length of the String array is:"+args.length);
for(int i=0; i<args.length; i++)
System.out.println("args[" + i + "]: " +args[i]);
}
}
Sample Program:
class Book {
String id;
String title;
String author;
void getChaptersList() {
id="Adv1";
title="Servlets";
author="Srinivasa Reddy";
System.out.println("Getting the chapters list");
System.out.println("ID:"+id);
System.out.println("Title:"+title);
System.out.println("Author:"+author);
System.out.println("-------------------------");
}
public static void main(String[] args) {
Book book1 = new Book();
book1.getChaptersList();
urtrainer.java@gmail.com
Java Fundamentals JAVA CSREDDY
Book book2 = new Book();
book2.getChaptersList();
}
}
import java.io.*;
class Emp
{
public static void main(String args[])throws Exception
{
//BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
InputStreamReader is=new InputStreamReader(System.in);
BufferedReader br=new BufferedReader(is);
System.out.println("Employee Number:");
int eno=Integer.parseInt(br.readLine());
System.out.println("Employee Name:");
String ename=br.readLine();
System.out.println("Employee Salary:");
float sal=Float.parseFloat(br.readLine());
System.out.println("Employee Details:");
System.out.println("------------------");
System.out.println("Employee Number:"+eno);
System.out.println("Employee Name:"+ename);
System.out.println("Employee Salary:"+sal);
}
}
urtrainer.java@gmail.com
Java Fundamentals JAVA CSREDDY
Sample:
import java.io.*;
class Bank
{
public static void main(String args[]) throws IOException
{ int i,j;
String[] ename;
ename=new String[30];
String[] bname;
bname=new String[30];
String[] type;
type=new String[30];
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
for(i=0;i<=2;i++)
{ System.out.println("Enter the name:");
ename[i]=br.readLine();
System.out.println("Enter the bank name:");
bname[i]=br.readLine();
System.out.println("Enter the accnt type:");
type[i]=br.readLine();
}
System.out.println("name bank actype");
for(j=0;j<=2;j++)
{
urtrainer.java@gmail.com
Java Fundamentals JAVA CSREDDY
System.out.println(ename[j]+" "+bname[j]+" "+type[j]);
}
}
}
Sample:
class Initialization {
boolean bo;
byte by;
char c;
short s;
int i;
long l;
float f;
double d;
Object o;
public static void main(String[] args) {
Initialization app = new Initialization();
app.run();
}
void run() {
System.out.println("boolean: " + bo);
System.out.println("byte: " + by);
System.out.println("char: " + c);
System.out.println("short: " + s);
System.out.println("int: " + i);
System.out.println("long: " + l);
System.out.println("float: " + f);
System.out.println("double: " + d);
System.out.println("Object: " + o);
}
urtrainer.java@gmail.com
Java Fundamentals JAVA CSREDDY
}
// -----------------------------------------------------------------------------
// MathLibraryExample.java
// -----------------------------------------------------------------------------
/**
* -----------------------------------------------------------------------------
* Used to provide an example that exercises most of the routines in
* java.lang.Math.
* @version 1.0
* @author Srinivasa Reddy Challa
* -----------------------------------------------------------------------------
*/
public class MathLibraryExample {
private static int i = 7;
private static int j = -9;
private static double x = 72.3;
private static double y = 0.34;
/**
* Helper utility used to print a String to STDOUT.
* @param s String that will be printed to STDOUT.
*/
private static void prt(String s) {
System.out.println(s);
}
private static void prt() {
System.out.println();
}
urtrainer.java@gmail.com
Java Fundamentals JAVA CSREDDY
/**
* Helper utility used to print all variables used through out all
* example Math methods.
*/
/**
* Round off a floating point number to the nearest integer with round().
* <p>
* The "ceiling" of a number is the smallest integer greater than or equal
* to the number. Every integer is its own ceiling.
* <p>
* The "floor" of a number is the largest integer less than or equal to the
* number. Every integer is its own floor.
*/
private static void doTruncateRounding() {
prt("TRUNCATING AND ROUNDING FUNCTIONS");
prt("===========================================");
prt(" " + x + " is approximately " + Math.round(x));
prt(" " + y + " is approximately " + Math.round(y));
prt();
prt(" The ceiling of " + i + " is " + Math.ceil(i));
prt(" The ceiling of " + j + " is " + Math.ceil(j));
prt(" The ceiling of " + x + " is " + Math.ceil(x));
prt(" The ceiling of " + y + " is " + Math.ceil(y));
prt();
prt(" The floor of " + i + " is " + Math.floor(i));
prt(" The floor of " + j + " is " + Math.floor(j));
prt(" The floor of " + x + " is " + Math.floor(x));
prt(" The floor of " + y + " is " + Math.floor(y));
prt();
urtrainer.java@gmail.com
Java Fundamentals JAVA CSREDDY
}
/**
* Comparison operators. min() returns the smaller of the two arguments
* (numbers) you pass it.
* <p>
* max() returns the the larger of the two arguments (numbers) you pass it.
*/
private static void doComparisonOperators() {
prt("COMPARISON OPERATORS");
prt("===========================================");
prt(" min(" + i + ", " + j + ") is " + Math.min(i,j));
prt(" min(" + x + ", " + y + ") is " + Math.min(x,y));
prt(" min(" + i + ", " + x + ") is " + Math.min(i,x));
prt(" min(" + y + ", " + j + ") is " + Math.min(y,j));
prt();
prt(" max(" + i + ", " + j + ") is " + Math.max(i,j));
prt(" max(" + x + ", " + y + ") is " + Math.max(x,y));
prt(" max(" + i + ", " + x + ") is " + Math.max(i,x));
prt(" max(" + y + ", " + j + ") is " + Math.max(y,j));
prt();
}
/**
* Trigonometric Methods. All arguments are given in radians.
*/
private static void doTrigonometricMethods() {
prt("TRIGONOMETRIC METHODS");
prt("===========================================");
urtrainer.java@gmail.com
Java Fundamentals JAVA CSREDDY
// Convert a 45 degree angle to radians
double angle = 45.0 * 2.0 * Math.PI/360.0;
prt(" cos(" + angle + ") is " + Math.cos(angle));
prt(" sin(" + angle + ") is " + Math.sin(angle));
urtrainer.java@gmail.com
Java Fundamentals JAVA CSREDDY
/**
* Using Power Method. pow(x, y) returns the x raised to the yth power.
*/
private static void doPower() {
prt("POWER METHOD");
prt("===========================================");
prt(" pow(2.0, 2.0) is " + Math.pow(2.0,2.0));
prt(" pow(10.0, 3.5) is " + Math.pow(10.0,3.5));
prt(" pow(8, -1) is " + Math.pow(8,-1));
prt();
}
/**
* Using Power Method. qrt(x) returns the square root of x.
*/
private static void doSquareRoot() {
prt("SQUARE ROOT METHOD");
prt("===========================================");
for (i=0; i < 10; i++) {
prt(" The square root of " + i + " is " + Math.sqrt(i));
}
prt();
}
/**
* Random Numbers. Java provides a Random method that returns a
* pseudo-random number between 0.0 and 1.0.
*/
urtrainer.java@gmail.com
Java Fundamentals JAVA CSREDDY
private static void doRandomNumbers() {
prt("RANDOM NUMBERS");
prt("===========================================");
prt(" Random number: " + Math.random());
prt(" Random number: " + Math.random());
prt(); }
public static void main(String[] args) {
prt();
printVariables();
printMathConstants();
doAbsoluteValues();
doTruncateRounding();
doComparisonOperators();
doTrigonometricMethods();
doExponentialLogarithmicMethods();
doPower();
doSquareRoot();
doRandomNumbers();
}
}
Constructors in Java:
A constructor is a special member method which will be called by the JVM
automatically whenever an object is created for placing our own values instead of
placing default values.
Advantages:
1) It eliminates in placing default values
2) It eliminates the calling of ordinary methods explicitly; the purpose of the
constructors is that to initialize an object.
Rules / Properties / Characteristics of Constructors
1) Constructor will be called automatically whenever an object is created.
2) The name of the constructor must be similar to name of the class.
urtrainer.java@gmail.com
Java Fundamentals JAVA CSREDDY
3) Constructor should not return any value, even void also. [ if we write any return
type which is by default treated as ordinary method ]
4) Constructors should not be static since they will be called each and every time as
and when an object is created.
5) Constructors will not be inherited.
Types of Constructors:
In Java we have 2 types of constructors. They are
a) Default / Parameter Less/ No Argument Constructor
b) Parameterized Constructor
Note:
Defining default constructor is optional. If we are not defining the default constructor
then JVM will call its own constructor called system defined constructor and it places
default values depending upon data type. If we define the default constructor of the
class, then JVM will call the user defined constructor for placing our own values.
Note:
Each and every class contains the default constructor.
class Test
{ int a,b;
Test()
{ a=10;
b=20;
System.out.println("I am from Dconstructor");
System.out.println("Value of a="+a);
System.out.println("Value os b="+b);
}
}
class Con_Demo1
{
public static void main(String args[])
{
urtrainer.java@gmail.com
Java Fundamentals JAVA CSREDDY
Test t1=new Test();
}
}
Q) Write a sample program to get values into the constructor at runtime? One
is by using BufferedReader Class, DataInputStream Class? (Get Empno, Ename,
Job, and Salary and print it by using other function or method?
Parameterized Constructor:
Parameterized Constructors are used for creating multiple objects of same class
with different values.
Parameterized Constructor is one which always takes parameters.
class name
{ ---
ClassName(list of arguments or formal parameters)
{ // Block of Statements;
}
}
Program:
class Test
{ int a,b;
Test(int x,int y)
{ a=x;
b=y;
System.out.println("I am from Parameterized constructor");
System.out.println("Value of a="+a);
System.out.println("Value os b="+b);
}
}
class Con_Demo2
{ public static void main(String args[])
{
Test t1=new Test(1,2);
urtrainer.java@gmail.com
Java Fundamentals JAVA CSREDDY
Test t2=new Test(10,20);
Test t3=new Test(100,200);
}
}
Note Point 1) Whenever we create an object using parameterized constructor defining
parameterized constructor is mandatory.
Note Point 2) Whenever we create multiple objects with both default and
parameterized constructors, it is mandatory for the java programmer to define both
parameterized and default constructors. Otherwise, we get compile time errors.
Overloaded Constructor:
Every Overloaded Constructor is a parameterized constructor and it is mandatory
to define.
A constructor is said to be overloaded if constructor name is same but its
signature is different.
Signature represents
a) Number of Parameters
b) Type of Parameters // At least one thing must be differentiated
c) Order of Parameters
Object Parameterized Constructor or Copy Constructor
It is one which takes object as a parameter.
Note: Object parameterized constructor is used for copying the content of one object to
another object. And both the objects must belong to same type.
class Test {
int a,b;
Test(int x,int y) { a=x; b=y;
System.out.println("Value of a="+a);
System.out.println("Value os b="+b);
}
Test(Test t) { a=t.a; b=t.b;
System.out.println("Value of a="+a);
System.out.println("Value os b="+b);
}
urtrainer.java@gmail.com
Java Fundamentals JAVA CSREDDY
}
class Con_Demo3
{ public static void main(String args[])
{ Test t1=new Test(10,20);
Test t2=new Test(t1);
} }
this keyword Usage:
“this” is a keyword / implicit object created by JVM for 2 purposes. They are
1) It points to current class object
2) Whenever formal parameters and data members of the class are similar, there is a
possibility of ambiguity. In order to differentiate between formal parameters and
Data Members of the class, the data members of the class must be proceeded by a
keyword “this”
this.currentclassdatamember;
class Sample
{ int a,b;
Sample(int a, int b)
{
this.a=a;
this.b=b;
}
void disp()
{
System.out.println("Value of a="+a);
System.out.println("Value of b="+b);
}
}
class This1
{
public static void main(String args[])
{
Sample s1=new Sample(10,20);
urtrainer.java@gmail.com
Java Fundamentals JAVA CSREDDY
s1.disp();
Sample s2=new Sample(2,15);
s2.disp();
}
}
this(),this(…):
In order to call the current class constructors we must use the following functions.
this():
It is used for calling current class default constructor from current class parameterized
constructors.
this(..,..):
It is used for calling current class parameterized constructors from other category
constructors of same class.
Note:
Whenever we use either this() or this(...,…) in the current class constructors, they must
be always used as first statement.
Sample:
class Sample
{int a,b;
Sample()
{ System.out.println(" I Am From Deafault Constructor");
a=1; b=2;
System.out.println(" Value of a="+a);
System.out.println(" Value of b="+b);
}
Sample(int x)
{ this(10,20);
System.out.println(" I am from SPCons");
a=b=x;
System.out.println(" Value of a="+a);
System.out.println(" Value of b="+b);
urtrainer.java@gmail.com
Java Fundamentals JAVA CSREDDY
}
Sample(int a,int b)
{ this();
System.out.println(" I am from DPConstructor");
this.a=a;
this.b=b;
System.out.println(" Value of a="+a);
System.out.println(" Value of b="+b);
}
}
class This2
{ public static void main(String args[])
{
Sample s1=new Sample (100);
}
}
Inheritance:
Inheritance is a mechanism of getting the features from one class to another class.
The class which is giving the data members and methods is known as
Base/Parent/Super Class. The class which is taking data members is known as derived.
Derived Class: Derived Class is one which contains some of the features of its own plus
some of the features from Base Class. Features of a class are nothing but Data Members
and Methods. The process of inheritance is also known as Sub Classing/Reusability
/Derivation/Extendibility.
Advantages of Inheritance:
Application Development time is less.
Redundancy of the code is reduced. Hence we get consistent result plus less
execution time.
urtrainer.java@gmail.com
Java Fundamentals JAVA CSREDDY
Application Memory Space is reduced. Hence we get effective performance and
reduced memory space.
Inheritance Types:
Based on getting the features from one class to another class java contains 5 reusable
techniques / Inheritance Types.
They are: Single Inheritance , Multi Level, Hierarchical, Multiple, Hybrid Inheritance.
Single Inheritance:
It is one in which there exists single base class and single derived class.
Multi Level Inheritance:
It is one in which there exists single base class, single derived class and ‘n’ number of
intermediate base classes. Intermediate base class is one in one context it acts as base
class and in another context the same class acts as derived class.
C1 (Base Class) C2 (DC &BC) C3 (DC &BC) C4 Derived Class.
IBC IBC
Hierarchical Inheritance:
It is one in which there exists single base class and ‘n’ number of Derived Classes.
C1 is a Base Class For that We are having C2, C3, C4 etc are derived Classes.
Multiple Inheritance:
It is one in which there exists Multiple Base Classes and Single Derived Class.
Java does not support multiple Inheritance through the concept of classes but it can be
supported by Java through the concept of interfaces.
Syntax for inheriting the features from base class to derived class.
class <ClassName> extends <Super Class Name>
urtrainer.java@gmail.com
Java Fundamentals JAVA CSREDDY
{
//Variable Declaration;
// Methods definition;
}
extends is a keyword which is used for inheriting the features of Base Class
into derived class plus it improves the functionality of Derived Class.
class bc
{ int a;
void disp1(){ System.out.println("Display Base Class");}
}
class dc extends bc
{ int b;
void disp2() { System.out.println("Display Of Derived class");
urtrainer.java@gmail.com
Java Fundamentals JAVA CSREDDY
a=10; b=20;
System.out.println("Value of a="+a);
System.out.println("Value of b="+b); }
}
class idemo1
{ public static void main(String args[]) {
dc d=new dc();
d.disp1();
d.disp2();
}
}
Multi Level Demo:
class Admin
urtrainer.java@gmail.com
Java Fundamentals JAVA CSREDDY
System.out.println("\nStaff Salary : "+sal); }
}
class MultiLevelDemo
{ public static void main(String args[])
{ Accountant a=new Accountant();
a.getDetails(25,28);
a.printSal();
} }
Hierarchical Demo:
class Eng{ int dur; double fees;
public Eng() { dur=4; fees=20000.00; }
protected void disp() { System.out.println("\nThe Duration is : "+dur);
System.out.println("The Fees is : "+fees);
}
}
class EEE extends Eng { String s1,s2,s3;
public EEE(String s1,String s2,String s3)
{ this.s1=s1; this.s2=s2; this.s3=s3; }
public void display() { disp();
System.out.println("The Subjects are");
System.out.println("Subject 1 :"+s1);
System.out.println("Subject 2 :"+s2);
System.out.println("Subject 3 :"+s3); }
}
class CSIT extends Eng
{ String s1,s2,s3;
public CSIT(String s1,String s2,String s3)
{ this.s1=s1; this.s2=s2; this.s3=s3; }
public void display() { disp();
System.out.println("The Subjects are ");
System.out.println("Subject 1 :"+s1);
System.out.println("Subject 2 :"+s2);
System.out.println("Subject 3 :"+s3); }
urtrainer.java@gmail.com
Java Fundamentals JAVA CSREDDY
}
class HeirarchialDemo
{ public static void main(String args[]) {
EEE e=new EEE("Electronics","Maths","Physics");
CSIT c=new CSIT("Computers","Power Systems","Maths");
e.display();
c.display();
}}
Super Keyword:
In order to differentiate the base class features and derived class features we use a
keyword ‘super’. The keyword ‘super’ is placing an important role in 3 places. They
are
At Variable Level
At Method Level
At Constructor Level
urtrainer.java@gmail.com
Java Fundamentals JAVA CSREDDY
{
dc d=new dc();
d.disp();
}
}
Note: In the above program if we remove ‘super’ keyword then the current disp() will
be called by itself recursively and finally we get an error at runtime. Known as
java.lang.StackOverFlowError
Method Overriding:
Method Overriding=Method Heading is same but method body is different.
(or)
Method over riding is a process of redefining the original method in various
derived classes by inheriting the original method from base class.
urtrainer.java@gmail.com
Java Fundamentals JAVA CSREDDY
d.sum();
}
}
How do you call the original method from overridden method?
ANS: super.originalmethodname();
The above statement must be written in the context of derived class overridden
method.
Rule:
Whenever we use either super(), super(..) in the derived class constructors,
they must be used as first statement.
Note: Important Points:
Whenever we want to call base class default constructor from derived class
constructors we have to use super() in the context of derived class constructor.
Writing super() in the context of derived class constructor is optional.
/* Super at Constructor Level */
class c1 { int a,b;
c1() { System.out.println("c1 deafault constructor");
a=10; b=20;
System.out.println("Value of a:"+a);
System.out.println("Value of b:"+b); }
}
class c2 extends c1 { int c,d;
c2() { super();
System.out.println("c2 deafault constructor");
urtrainer.java@gmail.com
Java Fundamentals JAVA CSREDDY
c=30; d=40;
System.out.println("Value of C:"+c);
System.out.println("Value of d:"+d); }
}
class idemo4 { public static void main(String args[])
{ c2 o2=new c2();
}
}
class c1
{ int a,b;
c1(int a,int b)
{
this.a=a;
this.b=b;
System.out.println("C1 Par Constructor");
System.out.println("Value of a:"+a);
System.out.println("Value of b:"+b);
}
}
class c2 extends c1
{ int c,d;
c2()
{ super(10,20);
System.out.println("C2 Defalut Constructor");
c=30;
d=40;
System.out.println("Value of c:"+c);
System.out.println("Value of d:"+d);
urtrainer.java@gmail.com
Java Fundamentals JAVA CSREDDY
}
}
class idemo5
{ public static void main(String args[])
{ c2 o2=new c2();
}
}
Polymorphism:
Polymorphism is one of the oops principle. “It is a process of representing one
form in multiple / may forms”.
The principle of polymorphism is implemented in java programmatically by using
the concept of method overriding. In object oriented programming we have 2 types
of polymorphisms. They are
1) Static Polymorphism
2) Dynamic Polymorphism
Static Polymorphism:
It is one in which the method binds with an object at compile time and normally
space is created for the methods at compile time only.
The disadvantage of static polymorphism is that “Poor Utilization of Memory
Space”. To avoid this limitation we must use runtime polymorphism.
Runtime Polymorphism:
It is one in which method binds with an object at runtime and memory space for
the method will be allocated at runtime. The advantage of runtime polymorphism is that
effective utilization of memory space.
In real time applications when we are developing multiple applications with the
similar type of logic, it is always recommended to write with the concept of
polymorphism.
Dynamic Binding:
Dynamic binding always says that “Don’t create an object of derived class
but create an object of the base class”.
The basic aim of dynamic binding is that to execute polymorphism applications.
The purpose of dynamic binding is that to increase the performance of an
application by reducing the amount of memory space.
Definition:
urtrainer.java@gmail.com
Java Fundamentals JAVA CSREDDY
Dynamic Binding is a mechanism of binding an appropriate version of derived class
which is inherited from base class with base class object.
Note:
While we are executing polymorphism application with dynamic binding concept,
internally 2 points will be considered
by int a,b,c; JVM
1) What type of Object
void sum() 2) What type of address object
{ contains
Eg: a=10;
Let us b=20; consider the following entries which
will execute the program which was
c=a+b;
developed in the bellow diagram.
Sop(“Int Sum==”+c);
}
Consider the following Diagram:
C1 Class
char c1,c2,c3;
void sum()
c1=’A’;
c2=’B’;
c3=c1+c2;
Class C3
urtrainer.java@gmail.com
Java Fundamentals JAVA CSREDDY
Class C2 Sop(“Int Sum==”+c3);
float f1,f2,f3; }
void sum()
f1=10;
f2=20;
f3=f1+f2;
Sop(“Float Sum=”+f3);
1) C1 o1;
2) o1=new C1();
3) o1.sum();
4) o1=new C2();
5) o1.sum();
6) o1=new C3();
7) o1.sum();
In the statements (2), (4), (6) the object o1 contains an address of classes C1, C2,
C3. Hence the object o1 is known as Polymorphic Object.
The sum() is only one and it was implemented for performing various sums. Hence
sum() is known as polymorphic method.
In statements (3), (5), (7) o1.sum() is one but it gives different sum’s. Hence
o1.sum() is called polymorphic statement.
Note:
In order to use the features of one class into another class java contains 3
types of Relationships. They are
urtrainer.java@gmail.com
Java Fundamentals JAVA CSREDDY
1) Is- a Relationship: It is one in which the features of one class are inherited into
another class by using inheritance with extends keyword.
class C1
{ …
…
}
class C2 extends C1
{
…
…
}
2) Has a relationship: It is one in which the object of one class is created as a data
member in another class.
class C1
{ …
…
}
class C2 { …
…
C1 o1=new C1(); //Has a Relationship
}
3) Uses a Relationship:
A Factory method is one whose return type must be similar to name of the class where it
belongs to.
The purpose of Factory Method is that to create an object of the class without
using new operator.
1) The return type of Factory Method must be similar to name of the class where it
belongs to.
2) Every Factory Method in java must be static
3) Every Factory Method is recommended to make it to belong to public.
Abstract Classes:
Each and every program in java must be developed with respect to classes. Java
contains 2 types of classes. They are 1) Concrete Classes 2) Abstract Classes
An Abstract class is one which contains some defined methods plus some undefined
methods. Undefined methods of java are known as abstract or un implemented
methods. Once the class is abstract, whose class object cannot be created / instantiated
directly but it can be instantiated indirectly.
Abstract Method: A method is said to be an abstract if which does not contain method
body / definition but it contains only prototype/declaration.
Syntax:
Note: abstract methods always make us to understand what a method can do?
Syntax:
{ …..
……
Since the class operation is an abstract class whose object cannot be created directly but
it can be created indirectly.
Or
Note: Abstract classes of java make use of polymorphism along with method
overriding and dynamic binding.
urtrainer.java@gmail.com
Java Fundamentals JAVA CSREDDY
c=a+b;
System.out.println("int sum="+c);
}
}
class fsum extends operation { float a,b,c;
void sum() { a=100.25f; b=200.75f;
c=a+b;
System.out.println("Float Sum="+c);
}
}
class abdemo { public static void main(String args[]) {
//operation op=new operation(); invalid
operation op;
op=new isum();
op.sum();
op=new fsum();
op.sum();
}
}
Abstract classes are always reusable since they contain common purpose
methods.
Abstract Base Class: An abstract base class is one which contains logical
representation of abstract methods which are inherited from abstract base class.
With respect to abstract base class and abstract derived class we cannot create an
object directly but we can create indirectly.
If the derived class inherits ‘n’ number of abstract methods from abstract base
class and if the derived class is not defining at least one abstract method then the
current derived class is known as abstract and whose definition must be made
abstract by using ‘abstract’ keyword.
urtrainer.java@gmail.com
Java Fundamentals JAVA CSREDDY
If the derived class defines all n –number of abstract methods then the current
derived class is known as concrete derived class.
Both abstract base class and abstract derived class are always re usable by
derived classes.
Program:
abstract class c1 {
abstract void f1();
abstract void f2();
}
abstract class c2 extends c1 {
void f1() {
System.out.println("F1 Defined in c2");
}
}
class c3 extends c2 {
void f2() {
System.out.println("F2 Defined in C3");
}
void f1() {
super.f1();
System.out.println("F1 Defined in c3");
}
void f3() {
System.out.println("F3 defined in c3");
}
}
class abdemo1 {
public static void main(String args[]) {
System.out.println("With Respect to C3");
c3 o3 = new c3();
o3.f1();
o3.f2();
o3.f3();
System.out.println("With Respect to C2");
// c2 o2=new c2(); invalid
c2 o2;
o2 = new c3();
urtrainer.java@gmail.com
Java Fundamentals JAVA CSREDDY
o2.f1();
o2.f2();
// o2.f3(); in valid
System.out.println("With Respect to C1");
// c1 o1=new c1(); invalid
c1 o1;
o1 = new c3();
o1.f1();
// o1.f2();invalid
// o1.f3(); invalid
}
}
Note: We can make a concrete class as abstract if require. For
that we need to place an abstract keyword in front of class
definition.
Null Body methods are those which contain method definition but
there is no block of statements. Hence in java null body methods
are always overridden in derived classes.
Interfaces:
The concept of interfaces can be developed by using a keyword ‘interface’.
The concept of interface supports multiple inheritance.
The scope of interfaces is more than scope of abstract classes.
Definition: An interface is a collection of general purpose methods and general purpose
data members (or) is a collection of public static final data members and public abstract
methods (or) it is a construct which contains purely abstract methods and common
purpose data members;
Syntax:
interface <interface name>
{
urtrainer.java@gmail.com
Java Fundamentals JAVA CSREDDY
variable declaration cum intialization;
methods declaration;
}
interface is a keyword which is used for developing user defined data types.
An Object of interface cannot be created directly, but it can be created indirectly.
All the variables in the interface must be initialized since they are meant for
common purpose. Hence all the variables of interface are by default belongs to
public static final xxx data members. Hence xxx represents data type, variable
name and variable value.
Whatever the methods we are using in the interface are undefined methods and to
make them as abstract, java programmer need not to use a keyword abstract
explicitly.
Since the methods of interface can be accessed by everybody, explicitly we need
not write a keyword ‘public’.
Therefore all the methods of interface are default belongs to public abstract
methods.
All the features of interface are by default treated as Universal General Purpose
Reusable features.
Note: It is always recommended to keep all common purpose methods in
interfaces only but not in abstract classes.
Eg:
interface i1
{ int a=10; // public static final int a=10;
int b=20; // public static final int b=20;
void f1(); // public abstract void f1();
void f2(); // public abstract void f2();
}
Note:
Interfaces definition should not contain main();
Interfaces should not contain constructors
Interfaces are by default abstract only
Interfaces are not final since they are re usable by any number of subclasses.
urtrainer.java@gmail.com
Java Fundamentals JAVA CSREDDY
}
<ClassName> represents name of the derived class, <intf1>, <intf2> …,<intfn>
represents list of interfaces.
‘implements’ is a keyword used for inheriting the features either from one or
more than one interface into the derived class plus it improves the functionality of
derived class.
If the derived class inherits n number of abstract methods from interface(s) and if
the derived class is not defining at least one abstract method then the current
derived class must be made as abstract by ‘abstract’ keyword.
If the derived class defines all the abstract methods then the derived
class is known as concrete class.
One class can ‘extends’ one class at a time. But one class can implements
multiple interfaces.
Example:
interface i2 {
void f1();
}
interface i3 {
void f2();
}
class C11 implements i2, i3 {
public void f1() {
System.out.println("F1 Defined in C11 Class");
}
urtrainer.java@gmail.com
Java Fundamentals JAVA CSREDDY
It is a process of getting the features from either one or more than one interface to
another interface.
Syntax:
interface <intf1> extends <intf2>,<intf3>,…,<intfn>
{
Variable declaration cum initialization;
Methods declaration;
}
One class can extends only one class at a time where as one interface can extends
either one or more than one interface.
Syntax for Inheriting features from base class, various Interfaces to the
derived class:
Program:
interface i1 {
void f1();
}
interface i2 extends i1 {
void f2();
}
abstract class c1 {
void f3() {
// Null Body
}
}
abstract class c2 extends c1 implements i2 {
urtrainer.java@gmail.com
Java Fundamentals JAVA CSREDDY
public void f1() {
System.out.println("F1 Defined in C2");
}
void f3() {
System.out.println("F3 Redefined in C2");
}
}
class c3 extends c2 {
public void f2() {
System.out.println("F2 Defined in C3");
}
public void f1() {
System.out.println("F1 Redefined in C3");
}
void f3() {
System.out.println("F3 redefined in in C3");
}
void f4() {
System.out.println("F4 Special in c3");
}
}
class inter2 {
public static void main(String args[]) {
System.out.println("With Respect to C3");
c3 o3 = new c3();
o3.f1();
o3.f2();
o3.f3();
o3.f4();
System.out.println("With Respect to C2");
c2 o2 = new c3();
o2.f1();
o2.f2();
o2.f3();
// o2.f4(); invalid
System.out.println(" with respect to C1");
c1 o1 = new c3();
// o1.f1(); invalid
// o1.f2(); invalid
o1.f3();
// o1.f4(); invalid
System.out.println(" W r to I2");
i2 io2 = new c3();
urtrainer.java@gmail.com
Java Fundamentals JAVA CSREDDY
io2.f1();
io2.f2();
// io2.f3(); invalid
// io2.f4(); invalid
System.out.println("W r To I1");
i1 io1 = new c3();
io1.f1();
// io1.f2(); invalid
// io1.f3();
// io1.f4();
}
}
Packages:
A package is a collection of classes, interfaces and sub packages. A sub package is again
contains collection of classes, interfaces and sub sub packages.
Whenever the class/interface is common for much number of java programmers,
those classes & interfaces are recommended to keep into the package.
Advantages:
Application Development Time is less
Redundancy of code is reduced. Hence we get consistent result and faster
execution.
Every application takes less amount memory space. Hence we get high
performance.
Types of packages in Java:
In java programming we have 2 types of packages, they are 1) Predefined Packages
2) User / Custom defined packages.
Predefined Packages: Predefined Packages are those which are developed by Sun
Micro Systems and supplied as part of JDK to deal with Universal Requirements.
All the Predefined Packages of java are compressed in a single file called “rt.jar” , the
file rt.jar is located in JDK/JRE/LIB folder.
User Defined Packages: User Defined Packages are those which are developed by java
programmer and they are supplied as a part of their project to deal with common
specific requirements.
Types of Predefined Packages:
As a part of J2SE we have 8 essential packages. They are
java.lang.*: This package is used for achieving language functionalities such as
Displaying Data on to the console
Getting the command line arguments
Obtaining Garbage Collector
Conversion of data from String into fundamental and fundamental into String.
Dealing with runtime errors.
urtrainer.java@gmail.com
Java Fundamentals JAVA CSREDDY
Developing multi threading applications etc..
java.awt.*: This package is used for developing front end GUI / Windows applications.
This package contains various classes and interfaces which allows us to create various
GUI components.
Eg: Button b1=new Button(“save”);
Awt Stands for Abstract Windowing Tool Kit.
java.awt.event.*: event is a sub package of awt package. The event package contains
various classes and interfaces which provides life/behavior/functionality to the GUI
components.
Hence to develop a full pledged front end application we must deal with java.awt.* and
java.awt.event.* packages.
java.io.*: This package is used for dealing with file operations in file programming.
Some of the file operations are
Opening a file either in read/write mode.
Modifying data from the file
Deleting data from the file
Inserting data into the file etc...
java.applet.*: This package is used for developing distributed applications. This
package contains only one class known as applet.
Applet: An applet is a java program which runs in the context of browser / world wide
web.
Limitations of Applets:
Applets bring virus from the server to the local machine.
Applets are unable to provide enough security to prevent the confidential
information from unauthorized users.
java.net.*: This package is used for developing Client /Server applications or network
oriented applications the limitation of this package is that we are able to develop only
intranet applications but not internet applications.
java.text.*: This package is used for formatting of text, in other words it is used for
formatting Date and Time according to client requirements.
java.util.*: This package contains various classes and interfaces which improves the
performance of java applications. This package is also known as Collection Framework.
Collection Framework is a standardized mechanism of grouping of different type or
similar type of values into a single variable. This single variable is known as Collection
Framework variable.
User Defined Packages:
User Defined Packages are those which are developed by java programmer
and they are supplied as a part of their project to deal with common specific
requirements.
urtrainer.java@gmail.com
Java Fundamentals JAVA CSREDDY
Whenever the class/interface is common for much number of java
programmers, those classes & interfaces are recommended to keep it in our package i.e.
User Defined Package.
Each and every class and interface of java must belong to a package. All the
predefined classes & interfaces are belonging to predefined packages. If we develop any
user defined class or interface and if they are not belong to any user defined package
then JVM will assume its own package called “NONAME” to keep the set of user defined
classes and interfaces.
Creating user defined package is nothing but creating it as directory / folder in
the current working machine.
Syntax for creating Userdefined Packages:
package packname;
> package is a keyword used for creating user defined packages;
package pack1.pack2.pack3…..packn;
Here pack2 and pack3 and packn are sub packages;
Name of the packages must be java valid identifiers names.
ex:
package p1;
package p1.p2;
Rule:
When we use any package statement in the java program it should be always
used as first executable statement in the java program.
Steps or Guidelines:
Choose the appropriate package name and ensure the package statement must be
the first executable statement.
Choose the ClassName or interface name and ensure whose modifier must be
public.
The modifiers of the constructors of the class must be public.
The modifiers of the methods of the class/interface must be public.
Whichever class/interface we are writing in the package that name must be given
as filename with an extension of .java
Note:
At any point of time either we need to write the class or we need to
write the interface with in the package but not both of them at a time.
Syntax for compiling package classes and interfaces:
javac -d . ClassName/interfacename.java
urtrainer.java@gmail.com
Java Fundamentals JAVA CSREDDY
import statement: ‘import’ is a keyword used for importing either all the classes and
interfaces of a specific package or specific class or interface from the specific package.
import pname.*; importing all the classes and interfaces
import p1.p2.*;
Sample pgm:
package tp;
public class Test
urtrainer.java@gmail.com
Java Fundamentals JAVA CSREDDY
{ public Test()
{ System.out.println("Test constructor ");
}
public void display()
{ System.out.println("Test Disp");
}
}
Execution Logic Class:
import tp.Test;
class packdemo1
{
public static void main(String args [])
{ Test t1= new Test ();
t1.disp ();
}
Note: If any class contains main () then that class is not recommended to belong to
package since main () is defined according to individual requirement. If a class does not
contain any main () (treated as common class) then that class is recommended to place
in the package.
package mp;
public class Mul {
int n;
public Mul(int n) {
this.n = n;
}
public void table() {
for (int i = 1; i <= 10; i++) {
System.out.println (n + "*" + i + "=" + (n * i));
}
}
}
Execution Logic Class:
import mp.Mul;
public class packdemo2 {
urtrainer.java@gmail.com
Java Fundamentals JAVA CSREDDY
public static void main(String[] args) {
int n = Integer.parseInt(args[0]);
Mul m = new Mul(n);
m.table();
}
}
Example:
package ip;
public interface i1 {
void f1();
}
package cp;
public abstract class C1 {
public abstract void f2();
}
package cp;
import ip.i1;
public class C2 extends C1 implements i1 {
public void f1() {
System.out.println(" F1 Defined in C2 Class");
}
public void f2() {
System.out.println(" F2 Defined in C2 Class");
}
}
import ip.i1;
import cp.C1;
import cp.C2;
public class PackDemo4 {
public static void main(String[] args) {
System.out.println("With respect to C2 Class");
C2 o2 = new C2();
o2.f1();
o2.f2();
System.out.println("With respect to C1 Class");
C1 o1 = new C2();
// o1.f1(); in valid
o1.f2();
System.out.println("With respect to Interface ");
i1 io1 = new C2();
io1.f1();
urtrainer.java@gmail.com
Java Fundamentals JAVA CSREDDY
// io1.f2(); in valid
}
}
Access Modifiers:
Access Modifiers are those which are applied before the class or interface. In java
Access Modifiers are of 3 types. They are
1) abstract
2) public
3) final
public abstract and public final can be possible.
abstract final (or) final abstract – Not Possible.
Access Specifiers:
In Java we have 4 types of Access Specifiers are there.
1) private
2) default (it’s not a keyword remember)
3) protected
4) public
Access Specifiers are always applied before the data members and methods.
Access Specifiers are always make us to understand how to access the data / methods
within the package (class-class, interface-interface, and interface-class) and across the
package (class-class, interface-interface, interface-class).
Access Specifier can be either private or protected or public. If we are not
writing any Access Specifier then JVM by default treats it as ‘default’ access Specifier.
[access Specifier] [static] [final] data type v1[=val1],v2[=val2],…, vn[=valn];
Eg: public static final float p1=3.147f; for the method also same style of syntax
String Handling:
Character: A character is an identifier which is enclosed with in single quotes
eg: 'a','$','10'
Characters are represented by a data type called char.
String:
A String is a sequence of characters enclosed with in double quotes;
Eg: "java"
In java we have two types of classes to deal with strings.
They are
1) java.lang.String class
2) java.lang.StringBuffer class
urtrainer.java@gmail.com
Java Fundamentals JAVA CSREDDY
Differences Between String and StringBuffer:
urtrainer.java@gmail.com
Java Fundamentals JAVA CSREDDY
Instance methods of a String class can be accessed by object of String Class
public final int length ();To determine number of characters in the String Object.
Eg: 1) String s="java";
int no=s.length ();
Sop (no); //4
2) public final String trim();
This method is used for eliminating leading and trailing spaces.
String s=" JavaWorld ";
String s1=s.trim();
Sop (s1.length()); //9
3) public final String concat(String);
Concatenate to strings i.e. target String is concatenated with Source String
String s1="java";
String s2="program";
String s3=s1.concat(s2);
Sop(s3); // javaprogram
Note:
String s1="java";
String s2="prog";
String s3=s1+s2;
Sop(s3); //javaprog
String s3="JAVA";
b=s1.equals (s3);
Sop(b); //true
8) public final boolean equalsIgnoreCase(String);
String s1="JAVA";
String s2="java";
boolean b=s1.equalsIgnoreCase (s2); // true
StringConstructors Alone:
class StringConstructors {
public static void main(String args[]) {
String s1 = new String(); // empty string
char chars[] = { 'h', 'e', 'l', 'l', 'o' };
String s2 = new String(chars); // s2="hello";
byte bytes[] = { 'w', 'o', 'r', 'l', 'd' };
String s3 = new String(bytes); // s3="world"
String s4 = new String(chars, 1, 3);
String s5 = new String(s2);
String s6 = s2;
System.out.println(s1);
System.out.println(s2);
System.out.println(s3);
urtrainer.java@gmail.com
Java Fundamentals JAVA CSREDDY
System.out.println(s4);
System.out.println(s5);
System.out.println(s6);
}
}
Sample Programs and Some Additional Functions:
String a[] = { "Jan", "Feb", "Mar", "Apr", "May", "Jun",
"Jul", "Aug","Sep", "Oct", "Nov", "Dec" };
for (int j = 0; j < a.length; j++)
{
for (int i = j + 1; i < a.length; i++) {
if (a[i].compareTo(a[j]) > 0) {
String t = a[j];
a[j] = a[i];
a[i] = t;
}
}
System.out.println(a[j]);
}
Sample:
class RegionMatchesDemo
{ public static void main(String args[])
{
String str="Good, good!";
boolean b1,b2,b3,b4;
b1=str.regionMatches(6,"Good",0,4);
b2=str.regionMatches(true,6,"Good",0,3);
b3=str.regionMatches(true,6,"Good",0,4);
b4=str.regionMatches(false,6,"Good",0,4);
System.out.println("b1="+b1);
urtrainer.java@gmail.com
Java Fundamentals JAVA CSREDDY
System.out.println("b2="+b2);
System.out.println("b3="+b3);
System.out.println("b4="+b4);
/* Some specilized forms
boolean startsWith(String str)
boolean endsWith(String str)
*/
String str1="welcome";
System.out.println(str1.startsWith("wel"));
System.out.println(str1.endsWith("come"));
// overloaded form
System.out.println("welcome".startsWith("come",3));
System.out.println("welcome".startsWith("come",4));
}
}
StringBuffer Class:
StringBuffer is a class which is used for handling String data.
Whenever we create an object of StringBuffer by default we get
16 additional characters memory space. The content of StringBuffer can be changed.
Hence StringBuffer object is known as Mutable object.
Constructors:
StringBuffer();
urtrainer.java@gmail.com
Java Fundamentals JAVA CSREDDY
StringBuffer(StringBuffer);
StringBuffer(char []);
StringBuffer(String);
The above constructor is used for converting String object into StringBuffer object
I.e. converting immutable object into mutable object.
Eg: String s="java";
StringBuffer sb=new StringBuffer(s);
Sop(sb);
Instance Methods:
Eg:
String s="java";
StringBuffer sb=new StringBuffer(s);
Sop(Length="+sb.length());
Sop(Capacity="+sb.capacity());
3) public final StringBuffer reverse();
This method is used for obtaining sentence reverse of StringBuffer content
Eg: StringBuffer sb=new StringBuffer("java");
StringBuffer sb1=sb.reverse();
Sop(sb1);// avaj
urtrainer.java@gmail.com
Java Fundamentals JAVA CSREDDY
5) public final StringBuffer substring(int,int); similar to String Class functions
6) public final String toString():
This method is used for converting StringBuffer object into String object.
Ex:
StringBuffer sb=new StringBuffer ("java");
String s=sb.toString();
Sop(s);
Sample Program:
class StringBufferDemo {
public static void main(String args[]) {
StringBuffer sb = new StringBuffer("Jampani LTD");
System.out.println(sb);
sb.append(" Hyderabad");
System.out.println(sb);
sb.insert(8, "Pvt ");
System.out.println(sb);
sb.reverse();
System.out.println(sb);
sb.reverse();
System.out.println(sb);
sb.delete(17, 20);
System.out.println(sb);
sb.append(sb);
System.out.println(sb);
}
}
Program:
public class StringBufferApp {
public static void main(String args[]) {
StringBuffer sb = new StringBuffer(" is ");
sb.append("Hot"); // concatenation
sb.append('!');
sb.insert(0, "Java");
sb.append('\n');
sb.append("This is ");
sb.append(true);
System.out.println(sb);
System.out.println(sb.charAt(6));
sb.setCharAt(21, 'T');
sb.append('\n');
urtrainer.java@gmail.com
Java Fundamentals JAVA CSREDDY
sb.append("Java is #");
sb.append(1);
System.out.println(sb);
System.out.println("Converting StingBuffer Object to
String");
String s = sb.toString();
System.out.println(s);
}
}
Out put:
Java is Hot!
This is true
s
Java is Hot!
This is True
Java is #1
Converting StingBuffer Object to String
Java is Hot!
This is True
Java is #1
Program:
import java.io.BufferedReader;
import java.io.InputStreamReader;
class StringBuffer1 {
public static void main(String[] args) throws Exception {
BufferedReader in = new BufferedReader(new
InputStreamReader(System.in));
String str;
try {
System.out.print("Enter your name: ");
str = in.readLine();
str += " This is the example of SringBuffer class and it's
functions.";
urtrainer.java@gmail.com
Java Fundamentals JAVA CSREDDY
// Create a object of StringBuffer class
StringBuffer strbuf = new StringBuffer();
strbuf.append(str);
System.out.println(strbuf);
strbuf.delete(0, str.length());
// append()
strbuf.append("Hello");
strbuf.append("World");
// print HelloWorld
System.out.println(strbuf);
// insert()
strbuf.insert(5, "_Java ");
// print Hello_Java World
System.out.println(strbuf);
// reverse()
strbuf.reverse();
System.out.print("Reversed string : ");
System.out.println(strbuf);
// print dlroW avaJ_olleH
strbuf.reverse();
System.out.println(strbuf);
// print Hello_Java World
// setCharAt()
strbuf.setCharAt(5, ' ');
System.out.println(strbuf);
// print Hello Java World
// charAt()
System.out.print("Character at 6th position : ");
System.out.println(strbuf.charAt(6));
// print J
// substring()
System.out.print("Substring from position 3 to 6 : ");
System.out.println(strbuf.substring(3, 7));
// print lo J
// deleteCharAt()
strbuf.deleteCharAt(3);
System.out.println(strbuf);
// print Helo java World
// capacity()
System.out.print("Capacity of StringBuffer object : ");
System.out.println(strbuf.capacity()); // print 83
// delete() and length()
strbuf.delete(6, strbuf.length());
urtrainer.java@gmail.com
Java Fundamentals JAVA CSREDDY
System.out.println(strbuf);
// no anything
} catch (StringIndexOutOfBoundsException e) {
System.out.println(e.getMessage());
}
}
}
Out Put:
Enter your name: Challa Srinivasa Reddy
Challa Srinivasa Reddy This is the example of SringBuffer class
and it's functions.
HelloWorld
Hello_Java World
Reversed string : dlroW avaJ_olleH
Hello_Java World
Hello Java World
Character at 6th position : J
Substring from position 3 to 6 : lo J
Helo Java World
Capacity of StringBuffer object : 83
Helo J
Exception Handling:
Runtime Errors of java are known as Exceptions.
Definition: The process of converting system error messages into user friendly messages
is known as Exception Handling.
When we pass any invalid input to a java program, then there is a possibility
of generating runtime errors.
When exceptions happen in java program, automatically program execution
will be abnormally terminated and control comes out of the normal flow of the program.
Java contains distinct feature called Exception handling to build strong
applications in real time environment.
It is always recommended to the programmers to convert system error
messages into user friendly messages by using the feature called Exception Handling.
urtrainer.java@gmail.com
Java Fundamentals JAVA CSREDDY
Types of Exceptions:
In Java we have 2 types of Exceptions. They are
1) Predefined / Built in Exceptions
2) User /Custom Defined Exceptions
Predefined Exceptions:
Predefined Exceptions are those which are developed by Sun Micro Systems
and supplied as a part of JDK to deal with Universal Problems. Some of the Universal
problems are Division by Zero, Invalid Bounds of the Array, Invalid Format of Number
etc…
User /Custom Defined Exceptions:
User Defined Exceptions are those which are developed by java programmer and
supplied as a part of their project to deal with common specific problems such as
negative ages, negative salaries, invalid number of password characters etc..
Types of Predefined Exceptions:
Predefined Exceptions are of 2 types. They are
a) Asynchronous Exceptions
b) Synchronous Exceptions
Asynchronous Exceptions: are those which deal with Hardware Problems such as
power failures, keyboard, mouse, and mother board failures, memory problems etc.
To handle all Asynchronous exceptions there exist a predefined super class
called java.lang.Error
Synchronous Exceptions: are those which deals with programmatic errors.
Synchronous Exceptions are divided into 2 types.
They are
1) Checked Exceptions 2) Un-Checked Exceptions
Checked Exceptions: are those which are sub classes of java.lang.Exception class.
They are related to secondary memory.
Eg: FileNotFoundException, ClassNotFoundException, IOException
Un-Checked Exceptions:
are those which are sub classes of java.lang.RuntimeException
They are related to primary memory RAM
EG: ArithematicException, NumberFormatException, ArrayIndexOutOfBoundsException
Exception Handling Hierarchy Chart:
You know already java.lang.Object is a Super Class for all the Java Predefined /
User Defined Classes.
urtrainer.java@gmail.com
Java Fundamentals JAVA CSREDDY
urtrainer.java@gmail.com
Java Fundamentals JAVA CSREDDY
5. JRE is sending the type of exception to java Exception API
6. A) B) C) Java Exception API executes either java.lang.Error (A for Asynchronous),
or java.lang.Exception (B for checked) or java.lang.RuntimeException (C for
Unchecked) and obtains the specific exception.
7. Java Exception API gives an appropriate exception class to JRE
8. JRE gives appropriate Exception class to JVM
9. JVM creates an object of appropriate Exception Class
Eg: ArithematicException ae=new ArithematicException(“/by Zero”);
10. JVM generates the System Error Message on the console which is not
recommended.
11. As a java programmer it is highly recommended to convert system error
messages into user friendly messages by making use Exception Handling.
Handling the Exception:
To handle runtime errors/exceptions we use the following five keywords.
1) try
2) catch
3) finally
4) throws
5) throw
Syntax for handling Exceptions:
try { Block of Statement(s); Which cause problems at runtime
}catch(TypeofException obj1)
{ Block of statement(s); Which provides user friendly messages
} catch(TypeofException obj1)
{ Block of statement(s); Which provides user friendly messages
}…
finally { Block of Statements which will be executed compulsorily; }
Write a java program which illustrates the concept of try block, catch block and
finally block.
import java.io.*;
import java.lang.*;
import java.lang.RuntimeException.*;
class Exp1
{ public static void main(String args[])
{
try{ String s1=args[0];
String s2=args[1];
int x=Integer.parseInt(s1);
urtrainer.java@gmail.com
Java Fundamentals JAVA CSREDDY
int y=Integer.parseInt(s2);
int z=x/y;
System.out.println("Division="+z);
}catch(ArrayIndexOutOfBoundsException ab)
{ System.out.println("Pass Sufficient values from command prompt");
}catch(NumberFormatException nfe)
{ System.out.println("Pass Numerical Value");
}catch(ArithmeticException ae)
{ System.out.println("Dont enter zero for denominator");
}
finally
{
System.out.println("I am from finally");
}
}
}
Try block:
1) This is the block which contains block of statements which causes problems at
runtime.
2) When an exception occurs during the program execution in the try block, program
execution is abnormally terminated and control goes to an appropriate catch block
by skipping the rest of the statements.
3) After executing appropriate catch block control never goes to try block even we
use return statement in catch block.
4) Catch block must be followed immediately after try block, i.e. no intermediate
statements are allowed between try and catch blocks.
5) Each and every try block must contain at least one catch block but it is
recommended to write multiple catch’s to provide more user friendly messages.
6) One try block can contain another try block, i.e. nested try blocks can be possible.
Catch Block:
1) This is the block in which we write block of statements which provide user friendly
messages.
2) At any point of time only one catch block will execute out of n-number of catch
blocks.
3) Catch block will executes whenever an exception occurs in the try block.
4) In the catch block we declare an object of appropriate exception class and it will
internally referenced by the JVM whenever an exception taken place.
Finally Block:
urtrainer.java@gmail.com
Java Fundamentals JAVA CSREDDY
1) This is the block in which we write the block of statements which will relinquish
(releasing) the resources (Data Base, Files) which are obtained in try block.
2) Writing finally block is optional
3) Finally block will execute compulsorily.
Note:
1) When an exception occurs then a part of try block will execute, one appropriate
catch block and finally block will execute.
2) When no exception occurs then complete try block and finally block will execute
but no catch block will execute.
throws keyword:
throws is a keyword which gives an indication to the calling function to keep the called
function under try and catch blocks.
Whenever we develop any common method for group of programmers and if
the common method is having any problematic statements then we need to write the
type of exceptions as a part of method heading with a keyword throws.
Syntax of Throws Keyword:
return type methodname(list of formal parameters if any)throws Type of
Exception1,Type of Exception2, ...Type of Exception n
{
Block of Statement(s);
}
urtrainer.java@gmail.com
Java Fundamentals JAVA CSREDDY
{
int x=Integer.parseInt(args[0]);
int y=Integer.parseInt(args[1]);
Exp2 o1=new Exp2();
try
{ o1.div(x,y);
}
catch (NumberFormatException ne)
{ System.out.println ("Pass only Numeric values");
}
catch (ArithmeticException ae)
{ System.out.println ("Dont enter for denominator");
}
}
}
Finding the Details about un-known Exceptions:
When we write any java program there is a possibility of generating n number
of Runtime errors and those errors may not be known to java programmer. In order to
find the details about unknown exceptions we have 3 ways. They are
1) By using an object of java.lang.Exception
2) By using printStackTrace()
3) By using getMessage()
urtrainer.java@gmail.com
Java Fundamentals JAVA CSREDDY
Name of the Exception Nature of the Exception
Sample Program:
public class Exp1 {
public static void main(String[] args) {
try {
int x = Integer.parseInt("10x");
} catch (Exception e) {
System.out.println(e);
System.out.println(e.getMessage());
e.printStackTrace ();
}
}
}
Using getMessage ():
This is the method which is available in java.lang.Throwable class and it is further
inherited into java.lang.Exception and java.lang.Error classes.
Using this method we can display only nature of the message. The prototype
of the getMessage () is given bellow.
java.lang.Throwable public String getMessage();
Ex: try { …. int x=Integer.parseInt(10x);
…
}catch(Exception e)
{ System.out.println(e.getMessage()); }
Message: For input string: "10x"
Nature of the Exception
Using printStackTrace()
This is the method which is available in java.lang.Throwable class and it is further
inherited into java.lang.Exception and java.lang.Error classes.
Using this method we can find name of the exception, nature of the exception,
and the line number where the exception happens. The prototype of printStackTrace() is
given bellow.
java.lang.Throwable public void printStackTrace()
Ex:
try { …. int x=Integer.parseInt(10x);
…
}catch(Exception e)
urtrainer.java@gmail.com
Java Fundamentals JAVA CSREDDY
{
System.out.println(e.printStackTrace()); // Invalid We cannot use like this
e.printStackTrace();
}
Message:
java.lang.NumberFormatException: For input string:"10x" at line No: 2
Name of the Exception Nature of the Exception Line No
throw keyword:
throw is a keyword which is used for throwing the exceptions which are occurring as a
part of method body. It can also be used to through the predefined exceptions by
changing the existing nature of the message.
Syntax1:
Class name here represents name of the class and it should be subclass of either
java.lang.Exception or java.lang.RuntimeException
Syntax2:
throw along with throws keyword
Write a java program which illustrates the concept of throw and throws
keywords?
class Ex3
{ public void div(int x,int y)throws NumberFormatException,ArithmeticException
{ if(y==0)
{
ArithmeticException ae=new ArithmeticException("Dont Enter Zero for Denominator");
throw(ae);
}
int z=x/y;
System.out.println("Division in Ex3:"+z);
}
urtrainer.java@gmail.com
Java Fundamentals JAVA CSREDDY
}class Ex4
{ public static void main(String args[])
{ int x=Integer.parseInt(args[0]);
int y=Integer.parseInt(args[1]);
Ex3 o3=new Ex3();
try { o3.div(x,y);
}
catch(Exception e)
{ System.out.println(e.getMessage());
}
}
}
Write the differences between throw and throws keyword:
3 When we use throw keyword within When we use throws keyword as a part of
the method body, it is mandatory for method heading it is optional for the java
the java programmer to use throws programmer to use throw keyword as a
keyword as a part of method part of method body.
heading.
package UserDefinedException;
@SuppressWarnings("serial")
class InvalidAmountException extends Exception {
InvalidAmountException() {
super();
}
InvalidAmountException(String mesg) {
super(mesg);
}
}
class Bank { int accno, bal; String name;
void openAccount(int accno, int bal, String name)
throws InvalidAmountException {
if (bal < 1000)
throw new InvalidAmountException(
urtrainer.java@gmail.com
Java Fundamentals JAVA CSREDDY
"Initial Balence should be more than 1000");
this.accno = accno;
this.bal = bal;
this.name = name;
}
void getBalence() {
System.out.println("Current Balence : " + bal);
}
void deposit(int amount) {
bal = bal + amount;
}
void withDraw(int amt) throws InvalidAmountException {
int d;
d = bal - amt;
if (d < 1000)
throw new InvalidAmountException("You should not withdraw if the remaining
balance is less than 1000");
bal = bal - amt;
}
}
public class BankTest {
public static void main(String args[]) {
Bank b = new Bank();
try {b.openAccount(101, 2000, "Srinivas");
b.getBalence();
b.deposit(500);
b.getBalence();
b.withDraw(1900);
} catch (Exception e) {
System.out.println(e.getMessage());
} finally {
b.getBalence();
}
}
}
Collection Framework:
java.util.Collection:
1) It is available on top of hierarchy of all the collection framework interfaces.
2) An Object of Collection interface allows us to add duplicates.
3) Collection interface object displays the data in random order.
4) Collection interface object allows us to retrieve the data only in forward direction but
not in back word direction.
java.util.List:
1) An Object of List interface allows us to add the value either at specific position or
at end.
2) An Object of List interface allows us to add duplicates.
3) An Object of List interface displays the data in sorted order.
urtrainer.java@gmail.com
Java Fundamentals JAVA CSREDDY
4) An Object of List interface allows us to remove the data either in forward
direction or in back word direction or in both.
5) It allows multiple null values to be added.
Java.util.Set:
1) Set interface object allows us to add the value only at the end.
2) Set interface object does not allow duplicates.
3) Set interface object allows display the data in random order.
4) Set interface object allows retrieving the data in forward direction.
5) It allows only single null value.
java.util.SortedSet:
1) SortedSet interface object allows us to add the value only at the end.
2) SortedSet interface object does not allow duplicates.
3) SortedSet interface object allows display the data in sorted order.
4) SortedSet interface object allows retrieving the data in forward direction.
urtrainer.java@gmail.com
Java Fundamentals JAVA CSREDDY
System.out.print ("ArrayList arraylistB --> ");
while (i1.hasNext()) {
Object obj=i1.next();
System.out.print (obj + " , ");
}
Iterator Interface:
An object of Iterator Interface is used for extracting the
data from any Collection Framework Variable When we create an
object of Iterator which is by default pointing to just before
the first element and it extracts the data only in forward
direction.
Methods:
public boolean hasNext(); Is used for determining whether
we have next element or not. This method returns true when the
collection framework variable contains next element otherwise
this method returns false.
public Object next(); Is used for obtaining an element of
collection framework variable provided hasNext() method returns
true.
l.add(l.size(),new Integer(50));
*/
l1.remove(2);
System.out.println(" Object removed from 2 position
Successfully:" + l1);
/*
* Object set(int index, Object obj);
urtrainer.java@gmail.com
Java Fundamentals JAVA CSREDDY
*/
l1.set(0, "List");
System.out.print("\n Value is placed in position :" +
l1);
/*
* List subList(int start, int end);
*/
List l2=l1.subList(2, 6);
System.out.println("\n Sub list Elements are:"+l2);
System.out.println("ListIterator -FD");
ListIterator litr=l1.listIterator(); //Retriving the data
while(litr.hasNext())
{
Object obj2=litr.next();
System.out.println(obj2);
}
System.out.println("List Iterator-BD");
while(litr.hasPrevious())
{
Object obj3=litr.previous();
System.out.println(obj3);
}
Object obj=l1.get(2);
System.out.println("Element ="+obj);
}
}
Next Program:
@looping-through-a-collection-object
import java.util.ArrayList;
import java.util.Iterator;
public class CollectionDemo {
/**
* Example of iterating through a Collection object
*/
public void iterateCollection() {
ArrayList<String> list = new ArrayList<String>();
list.add("Monday");
list.add("Tuesdag");
urtrainer.java@gmail.com
Java Fundamentals JAVA CSREDDY
list.add("Wednesday");
list.add("Thursday");
list.add("Friday");
list.add("Saturday");
list.add("Sunday");
Iterator<String> iterator = null;
// Example 1:
iterator = list.iterator();
while (iterator.hasNext()) {
String element = iterator.next();
System.out.println(element);
}
// blank line
System.out.println();
// Example 2:
for (iterator = list.iterator(); iterator.hasNext();) {
String element = iterator.next();
System.out.println(element);
}
// blank line
System.out.println();
// Example 3:
for (String element : list) {
System.out.println(element);
}
}
public static void main(String[] args) {
new CollectionDemo().iterateCollection();
}
}
import java.util.LinkedList;
import java.util.List;
//Converting Linked List to Array
public class LtoA {
public void convertLinkedListToArray() {
List<String> theList = new LinkedList<String>();
//List theList=new LinkedList();
theList.add("Apples");
theList.add("Bananas");
theList.add("Oranges");
theList.add("Grapes");
urtrainer.java@gmail.com
Java Fundamentals JAVA CSREDDY
String[] fruits = theList.toArray(new String[0]);
for (int i = 0; i < fruits.length; i++) {
System.out.println(fruits[i]);
}
}
public static void main(String[] args) {
new LtoA().convertLinkedListToArray();
}
}
//@convert-a-list-arraylist-to-an-array
import java.util.*;
public class LAA {
public void ListToArray() {
List<String> carList = new ArrayList<String>();
carList.add("Dodge");
carList.add("Chevrolet");
carList.add("BMW");
carList.add("Toyota");
String[] carArray = carList.toArray(new String[0]);
}
}
/*
* get()
*/
System.out.println("2: " + list.get(2));
System.out.println("0: " + list.get(0));
LinkedList queue = new LinkedList();
queue.addFirst("Bernadine");
queue.addFirst("Elizabeth");
queue.addFirst("Gene");
queue.addFirst("Elizabeth");
queue.addFirst("Clara");
queue.addLast("Srinu");
queue.add(0,"Reddy");
System.out.println(queue);
System.out.println(queue.contains("Srinu"));
/*
* public Object removeFirst();
* public Object removeLast();
*/
queue.removeLast();
queue.removeFirst();
queue.removeLast();
System.out.println(queue);
/*
* getFirst() & getLast() methods will return an Object
* public Object getFirst();
* public Object getLast();
*/
System.out.println("getFirst():"+queue.getFirst());
System.out.println("getLast():"+queue.getLast());
/*
* toString() method converts Collection Object values into
String values
*/
System.out.println( queue.toString());
/*
* toArray() method converts Collection object into Object
array
*/
urtrainer.java@gmail.com
Java Fundamentals JAVA CSREDDY
System.out.println("******Usage of toArray()
Function******");
System.out.println(queue.toArray());
Object[] o1=queue.toArray();
for(int i=0;i<o1.length;i++)
{
System.out.println(o1[i]);
}
System.out.println("By For Each Loop");
for(Object i:o1)
{
System.out.println(i);
}
System.out.println();
// Checking emptiness of an ArrayList
System.out.println("Is arraylist empty? "
+ queue.isEmpty());
System.out.println();
// Checking for Equality of ArrayLists
ArrayList arraylistC = new ArrayList(queue);
System.out.println("queue.equals(arraylistC)? "
+ queue.equals(arraylistC));
System.out.println();
/*
* Collections class methods
*/
System.out.println("Collections Class Methods Output\n");
// Sort an ArrayList
System.out.print("Sorted ArrayList --> ");
Collections.sort(queue);
System.out.print(queue);
System.out.println();
// Reversing an ArrayList
System.out.print("Reversed ArrayList --> ");
Collections.reverse(queue);
System.out.println(queue);
System.out.println();
System.out.println();
// Shuffling the elements of an ArrayList in Random Order
Collections.shuffle(queue, new Random());
System.out.print("ArrayList after shuffling its elements--
> ");
Iterator i1 = queue.iterator();
urtrainer.java@gmail.com
Java Fundamentals JAVA CSREDDY
while (i1.hasNext()) {
System.out.print(i1.next() + " , ");
}
System.out.println();
/*
* Example for copy() method in Collections Class
*/
LinkedList queue1 = new LinkedList();
queue1.add("srinu");
queue1.add("vasu");
queue1.add("venkat");
queue1.add("java");
System.out.println(queue1);
System.out.println("********Collections Class copy()
Output\n");
Collections.copy(queue1,queue);
System.out.println(queue1);
/*
* public static int binarySearch(List list,Object key);
*/
System.out.println("********Collections Class
binarySearch(List list,Object key) Output\n");
int i=Collections.binarySearch(queue, "Gene");
System.out.println(i);
/*
* public static void swap(List list, int i,int j);
*/
System.out.println("********Collections Class swap(List list,
int i,int j) Output\n");
System.out.println(queue);
Collections.swap(queue, 0,2) ;
System.out.println(queue);
/*
* public static void fill(List list, Object obj);
*/
Collections.fill(queue, "Srinu");
System.out.println("Out Put for fill()");
System.out.println(queue);
/*
* public static Object min(Collection coll);
* public static Object max(Collection coll);
*/
urtrainer.java@gmail.com
Java Fundamentals JAVA CSREDDY
System.out.println("min and max functions");
System.out.println(Collections.min(queue1));
System.out.println(Collections.max(queue1));
System.out.println("End");
/*
* clear(); method
*/
queue.clear();
System.out.println(queue);
}
}
Methods in java.util.Set:
The Set Interface does not contain any special methods
except Collection Interface methods. Even though the methods are
same in both Set and Collection Interfaces their implementation
is different in different classes since Collection interface
allows duplicates and Set interface does not allow duplicates.
Methods in java.util.SortedSet:
import java.util.*;
public class CollectionsDemo {
@SuppressWarnings({ "rawtypes", "unchecked" })
public static void main(String[] args) {
List a1 = new ArrayList();
a1.add("Srinu");
a1.add("vasu");
a1.add("Reddy");
System.out.println(" ArrayList Elements");
System.out.print("\t" + a1);
List l1 = new LinkedList();
l1.add("Srinu");
l1.add("vasu");
l1.add("Reddy");
System.out.println();
System.out.println(" LinkedList Elements");
System.out.print("\t" + l1);
Set s1 = new HashSet();
urtrainer.java@gmail.com
Java Fundamentals JAVA CSREDDY
s1.add("Srinu");
s1.add("vasu");
s1.add("Reddy");
System.out.println();
System.out.println(" Set Elements");
System.out.print("\t" + s1);
SortedSet s11 = new TreeSet();
s11.add("Srinu");
s11.add("Vasu");
s11.add("Reddy");
System.out.println();
System.out.println(" SortedSet Elements");
System.out.print("\t" + s11);
Map m1 = new HashMap();
m1.put("Srinu", "8");
m1.put("Vasu", "31");
m1.put("Reddy", "12");
m1.put("Challa", "14");
System.out.println();
System.out.println(" Map Elements");
System.out.print("\t" + m1);
Map m2=new TreeMap();
m2.put("Srinu", "8");
m2.put("Vasu", "31");
m2.put("Reddy", "12");
m2.put("Challa", "14");
System.out.println();
System.out.println(" Map Elements");
System.out.print("\t" + m2);
}
}
LinkedList Class:
It is one of the bottom most concrete sub class of all
collection framework classes. An object of LinkedList allows us
to organize the data in the form of nodes. Node contains 2 parts
and whose structure you know already.
Data represents the type of value we are entering for the
LinkedList. Address part represents address of next node and for
the last node address part must be null which indicates end of
the LinkedList. So here explicitly memory is wasted for the
address. This is the drawback of LinkedList and one more is
retrieving is also takes time compared to ArrayList Class.
ArrayList Class:
It is one of the bottom most concrete sub class of all
collection framework classes. In ArrayList the data is organized
in the form of cells.
Creating ArrayList is nothing but creating an object of
ArrayList class.
Advantages:
1) Implicitly memory space is created for addresses for the
values of ArrayList in associative memory which leads to
less amount of memory space (Negligible).
urtrainer.java@gmail.com
Java Fundamentals JAVA CSREDDY
2) Retrieving the data from ArrayList is taking negligible
amount of time, i.e. Retrieval time of ArrayList is quite
fast.
HashSet and TreeSet Classes:
Collections Class:
Apart from above Collection Classes we have one more
Collection Framework Class is available for us to operate on
collection variables. We are having may predefined methods in
it.
Some Advanced Methods of List and Collections Class Methods:
Check at the above heading we are having the sample program
on Collections class methods.
import java.util.*;
public class SetDemo {
@SuppressWarnings({ "rawtypes", "unchecked" })
public static void main(String args[]) {
int count[]={34, 22,10,60,30,22};
Set<Integer> set = new HashSet<Integer>();
try{
for(int i=0; i<5; i++){
set.add(count[i]);
}
System.out.println(set);
TreeSet sortedSet=new TreeSet<Integer>(set);
System.out.println("The sorted list is:");
System.out.println(sortedSet);
}
catch(Exception e){}
}
}
The above methods are used for removing an entry of Map either based on
position or based on content i.e. key.
The last method is used for removing all the entries of Map.
urtrainer.java@gmail.com
Java Fundamentals JAVA CSREDDY
This method is used for obtaining Set of key values from the Map interface object and
pass these set of key values to get() for obtaining value of values.
Eg: Set s=m.keySet (); //s={10, 20, 30}
Iterator itr=s.iterator ();
while (itr.hasNext ())
{ Object kobj=itr.next ();
Object vobj=m.get(kobj);
System.out.println (vobj+”is the value of “+kobj);
}
Student Class:
package CollectionCaseStudy;
public class Student {
private String rollNo;
private String name;
private String address;
private String phone;
private String email;
urtrainer.java@gmail.com
Java Fundamentals JAVA CSREDDY
@Override
public String toString() {
return "Student [rollNo=" + rollNo + ", name=" + name + ",
address="
+ address + ", phone=" + phone + ", email=" + email +
"]";
}
}
StudentManager Class:
package CollectionCaseStudy;
import java.util.Iterator;
import java.util.List;
public class StudentManager {
public void printStudentDetails(List<Student> studentList) {
Iterator<Student> iterator = studentList.iterator();
while (iterator.hasNext()) {
Student student = iterator.next();
System.out.println("Student Roll No :" + student.getRollNo());
urtrainer.java@gmail.com
Java Fundamentals JAVA CSREDDY
System.out.println("Student Name :" + student.getName());
System.out.println("Student Address :" + student.getAddress());
System.out.println("Student Email :" + student.getEmail());
System.out.println("Student Mobile No :" + student.getPhone());
System.out.println("******************************************");
System.out.println("By Using Student Object with the help of toString()");
System.out.println(student);
System.out.println("******************************************");
}
}
}
MainClass:
package CollectionCaseStudy;
import java.util.ArrayList;
import java.util.List;
public class MainClass {
public static void main(String[] args) {
Student s1 = new Student("1", "Srinivas", "Flat No 123", "9603585810",
"urtrainer.java@gmail.com");
Student s2 = new Student("2", "Srinivasa Reddy", "Flat No 123/6A",
"9603585810", "urtrainer.java@gmail.com");
Student s3 = new Student("3", "Vasu", "Flat No 124/6B", "9603585810",
"urtrainer.java@gmail.com");
Student s4 = new Student("4", "Challa", "Flat No 125/6C", "9603585810",
"urtrainer.java@gmail.com");
Student s5 = new Student("5", "Csreddy", "Flat No 111/6E",
"9603585810", "urtrainer.java@gmail.com");
List<Student> studentList = new ArrayList<Student>();
studentList.add(s1);
studentList.add(s2);
studentList.add(s3);
studentList.add(s4);
studentList.add(s5);
new StudentManager().printStudentDetails(studentList);
}
}
Sample Program on Object Hash Code Values:
class Employee {
int id;
String name;
String add;
Employee(int id, String name, String add)
{ this.id = id;
this.name = name;
this.add = add;
}
Employee()
{ id = 112;
urtrainer.java@gmail.com
Java Fundamentals JAVA CSREDDY
name = "vasu";
add = "hyd";
}
}
public class Sample123 {
public static void main(String[] args) {
Employee o1 = new Employee(111, "srinu", "audipudi");
Employee o2 = new Employee(111, "srinu", "audipudi");
System.out.println(o1.hashCode());
System.out.println(o2.hashCode());
Employee t1 = new Employee();
Employee t2 = new Employee();
System.out.println(t1.getClass());
int a = t1.hashCode();
int b = t2.hashCode();
System.out.println("t1 object hash code: " + a);
System.out.println("t2 object hash code: " + b);
if (t1.equals(t2))
System.out.println("t1 and t2 refers the same");
else
System.out.println("t1 and t2 does not refer the same");
Employee t3, t4;
t3 = t1;
t4 = t1;
if (t3.equals(t4))
System.out.println("t3 and t4 refers the same");
else
System.out.println("t3 and t4 does not refer the same");
}
}
Utility Classes:
Calendar: This is used to set and get properties of Calendar. It is an abstract class.
Static Calendar getInstance () method is used to get the instance of the Calendar class.
urtrainer.java@gmail.com
Java Fundamentals JAVA CSREDDY
Methods: void set(int, int);
int get(int);
package utilpgms;
import java.util.Calendar;
class CalenderDemo {
public static void main(String args[]) {
Calendar cal = Calendar.getInstance();
System.out.println("Current Month : " + cal.get(Calendar.MONTH));
System.out.println("Current Day : " + cal.get(Calendar.DAY_OF_WEEK));
cal.set(Calendar.MONTH, Calendar.AUGUST);
cal.set(Calendar.DAY_OF_WEEK, 1);
//cal.set(Calendar.MONTH, 7);
System.out.println("Modified Month : " + cal.get(Calendar.MONTH));
System.out.println("Modfied Day : " + cal.get(Calendar.DAY_OF_WEEK));
System.out.println("Week of the Year : "
+ cal.get(Calendar.WEEK_OF_YEAR));
System.out.println("Year : " + cal.get(Calendar.YEAR));
}
}
DATE: This is used to know the date and time properties in date class, SUNDAY
-> 0..... SATUARDAY ->6, JANUVARY - 1.... DECEMBER – 12
Date (long);
int getDay();
int getYear();
urtrainer.java@gmail.com
Java Fundamentals JAVA CSREDDY
int getMonth();
int getHours();
int getMinutes();
int getSeconds();
void setDate(int);
void setDay(int);
void setYear(int);
void setMonth(int);
void setHours(int);
void setMinutes(int);
void setSeconds(int);
Depricated API:
API which is available in the older version, but not including the newer version is
called a Depricated API.
If we want to know, the depricated methods in our program, then we can compile
the program with the keyword
If we don’t want to get any warning then we should compile with the keyword
package utilpgms;
import java.util.Date;
public class DateDemo {
@SuppressWarnings("deprecation")
public static void main(String args[]) {
Date d = new Date();
System.out.println(d);
System.out.println(d.getDay());
System.out.println(d.getHours());
System.out.println(d.getDate());
System.out.println(d.getMinutes());
urtrainer.java@gmail.com
Java Fundamentals JAVA CSREDDY
System.out.println(d.getSeconds());
System.out.println(d.getYear() + 1900);
d.setDate(4);
System.out.println(d.getDate());
}
}
package utilpgms;
import java.util.Random;
public class RandomDemo {
public static void main(String args[]) {
Random r = new Random();
int ri = r.nextInt();
System.out.println("Int : " + ri);
ri = r.nextInt(100);
System.out.println("Limit Int : " + ri);
double rd = r.nextDouble();
System.out.println("Double : " + rd);
}
} Whatever the random value we are getting it may be a negative number or
positive number. If you want to get only positive number then you must use
Math.abs() method.
If you want to generate random number you have one more possibility that
is using Math. random () function and its return type is double data type.
Depending upon your requirement you go with your alternate option.
String Tokenizer :
This class is used to divide the given string into different tokens and that tokens
will be stored into a enumeration type. It will be divide the given string but we can’t
make any modifications on the given string.
boolean hasMoreTokens();
urtrainer.java@gmail.com
Java Fundamentals JAVA CSREDDY
boolean hasMoreElements();
String nextToken();
import java.util.StringTokenizer;
public class SplitString {
public static void main(String[] args) {
String str = "My name is Srinivas Reddy Challa";
String[] count = str.split(" ");
System.out.println("Number of Words:" + count.length);
String[] count1 = str.split("\\s+");
System.out.println("Number of Words:" + count1.length);
String str1 = "My name is Srinivas Reddy Challa";
StringTokenizer mytokens = new StringTokenizer(str1);
System.out.println("******************");
System.out.println("Number of Tokens:" + mytokens.countTokens());
System.out.println("******************");
while (mytokens.hasMoreElements())
System.out.println(mytokens.nextToken());
String str2 = "My, name, is, Srinivas Reddy ,Challa";
StringTokenizer mytokens1 = new StringTokenizer(str2, ",");
System.out.println("******************");
System.out.println("Number of Tokens:" + mytokens1.countTokens());
System.out.println("******************");
while (mytokens1.hasMoreTokens())
System.out.println(mytokens1.nextToken());
System.out.println("******************");
}
}
Stack: A Stack is one of the ordered list of elements, where it follows the order LIFO or
FILO. This class is used to perform all the stack operation and it is containing all built in
methods for that operations.
urtrainer.java@gmail.com
Java Fundamentals JAVA CSREDDY
package utilpgms;
import java.util.Stack;
class StackDemo {
@SuppressWarnings({ "rawtypes", "unchecked" })
public static void main(String args[]) {
Stack st = new Stack();
st.push("A");
st.push("B");
st.push("C");
st.push("D");
st.push("E");
st.push(new Integer(10));
System.out.println("Stack Peek value : " + st.peek());
System.out.println(st.search("D"));
System.out.println(st.empty());
for (int i = 0; i <= 5; i++)
System.out.println (st.pop());
System.out.println(st.search(new Integer(10)));
System.out.println(st.empty());
}
}
Out Put:
Stack Peek value : 10 3 false 10 E D C B A
-1
true
Dictionary: Dictionary is an abstract class that represents a key/value storage
repository and operates much like Map.
Hashtable : Hashtable was part of the original java.util and is a concrete
implementation of a Dictionary.
urtrainer.java@gmail.com
Java Fundamentals JAVA CSREDDY
Constructors:
Hashtable( )
Hashtable(Object key,Object value);
Methods: Object get(Object key);
Object put(Object key, Object value);
Object remove(Object key);
Enumeration keys( ) Returns an enumeration of the keys contained in the hash table.
Enumeration elements( )
Returns an enumeration of the values or elements contained in the hash table.
boolean hasMoreElements();
Properties : It is similar to Hashtable. This is a specially implemented to store the
key/value pair which are in the form of Strings.
Constructor: Properties ()
Methods: void setProperty(String,String);
String getProperty(String);
void list(PrintStream);
Program
package utilpgms;
import java.util.Properties;
class PropertiesDemo {
public static void main(String[] args) {
Properties p = new Properties();
p.setProperty("C", "Kanitkar");
p.setProperty("edition", "4th");
p.setProperty("Price", "150");
System.out.println("Author is :" + p.getProperty("C"));
System.out.println("Edition is :" + p.getProperty("edition"));
System.out.println("Price is :" + p.getProperty("Price"));
}
}
package utilpgms;
import java.util.LinkedList;
import java.util.Queue;
public class QueueDemo {
@SuppressWarnings({ "rawtypes", "unchecked" })
public void queueExample() {
urtrainer.java@gmail.com
Java Fundamentals JAVA CSREDDY
Queue queue = new LinkedList();
// Using the add method to add items.
// Should anything go wrong an exception will be thrown.
queue.add("item1");
queue.add("item2");
// Using the offer method to add items.
// Should anything go wrong it will just return false
queue.offer("Item3");
queue.offer("Item4");
// Removing the first item from the queue.
// If the queue is empty a java.util.NoSuchElementException will be
//thrown.
System.out.println("remove: " + queue.remove());
// Checking what item is first in line without removing it
// If the queue is empty a java.util.NoSuchElementException will be
// thrown.
System.out.println("element: " + queue.element());
// Removing the first item from the queue.
// If the queue is empty the method just returns false.
System.out.println("poll: " + queue.poll());
// Checking what item is first in line without removing it
// If the queue is empty a null value will be returned.
System.out.println("peek: " + queue.peek());
}
public static void main(String[] args) {
new QueueDemo().queueExample();
}
}
urtrainer.java@gmail.com
Java Fundamentals JAVA CSREDDY
Streams are used to read data from a source location or write data into a
destination location.
Here source can be a keyboard, a file, a disk. Destination can be file, disk, and
console.
Streams support different kinds of data streams, simple byte stream, primitive
data stream, character stream and object stream.
On files we can perform two operations. They are Read and Write Operations.
During the write operation if the selected file is read only file then we cannot
perform any write operation. Hence, we get an exception known as java.io.IOException.
During the write operation if there is no sufficient secondary memory space then
we get an exception known as java.io.IOException
In order to read the data from file which is residing in secondary memory into
primary memory, choose the filename open it into read mode and perform read
urtrainer.java@gmail.com
Java Fundamentals JAVA CSREDDY
operation. During read operation, if the specified file is not found, then we get an
exception called java.io.FileNotFoundException.
If we try to read the data from corrupted file we get an exception known as
java.io.IOException, you already aware that java.io.IOException is the super class for
java.io.FileNotFoundException.
Types of Streams:
Based on transferring the data between primary memory and secondary memory we
have 2 types of streams. They are 1) Byte Streams 2) Character Streams.
Byte Streams: Byte Streams are those which will transfer 1 byte of data between
primary memory and secondary memory. Byte Streams contain various classes and
interfaces which are used for opening the file in read mode and write mode and
performing various other operations. Byte Streams are internally implemented in lower
level applications such as flow of data across various electronic circuits, flow of data
across mother board circuits.
InputStream:
This is one of the super class for all Byte Stream classes which are related to read
operation.
Any object of InputStream class called ‘in’ created in System class as a static data
member(System.in)
InputStream class is one of the abstract whose object cannot be created directly,
but we can create indirectly and it is meant for opening a file in read mode.
Instance Methods:
public int available(): This method is used for determining the size of the file.
urtrainer.java@gmail.com
Java Fundamentals JAVA CSREDDY
public int read(); This method is used for reading the data from the file until end of file
is taking place. In java end of file is indicated by -1.
public void close(): This method is used for closing the file which was opened in read
mode.
OutputStream:
This is one of the Super Class for all Byte Stream classes related to write
operation.
This is one of the abstract class whose object can be created indirectly and it is
meant for opening a file in write mode.
public int available():
public void close():
public void write(int):
This method is used for writing the integer category data which was opened in
write mode.
DataInputStream Class: DataInputStream class is one of the bottom most concrete sub
class of all ByteStream classes. DataInputStream class is used for 2 purposes. They are
1) Reading the data from keyboard 2) Reading the data from other machine which
is located in another machine.
Constructor: DataInputStream(InputStream)
DataInputStream dis=new DataInputStream(System.in);
package Sample;
import java.io.DataInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
class DataRead {
public static void main(String args[]) {
try { DataInputStream dis = new DataInputStream(System.in);
System.out.println("Enter First number:");
String s1 = dis.readLine();
System.out.println("Enter Second number:");
String s2 = dis.readLine();
int x = Integer.parseInt(s1);
int y = Integer.parseInt(s2);
int z = x + y;
System.out.println("Sum:" + z);
} catch (FileNotFoundException e) {
System.out.println("Problem in Reading");
} catch (IOException e) {
System.out.println("Problem in reading corrupted file");
}
}
}
FileInputStream Class:
urtrainer.java@gmail.com
Java Fundamentals JAVA CSREDDY
FileInputStream Class is also one of the bottom most sub class of all Byte Stream
Classes. This class is used for opening a file in read mode.
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
/**
* @author Srinivasa Reddy Challa
*
*/
public class FileInputStream1 {
/**
* @param args
*/
public static void main(String[] args) {
StringBuffer content = null;
InputStream fileStream = null;
int ch;
String fname = "C://data.txt";
try { fileStream = new FileInputStream(fname);
content = new StringBuffer();
while ((ch = fileStream.read()) != -1) {
content.append((char) ch);
}
} catch (FileNotFoundException fileNotFound) {
fileNotFound.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
System.out.println(content);
try {
fileStream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
BufferedInputStream Class:
urtrainer.java@gmail.com
Java Fundamentals JAVA CSREDDY
import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.IOException;
/**
* @author Srinivasa Reddy Challa
*
*/
public class FileBufferTest {
/**
* @param args
*/
public static void main(String[] args) {
FileInputStream fileInput = null;
BufferedInputStream bufferInput = null;
try {
fileInput = new FileInputStream("C:/data.txt");
bufferInput = new BufferedInputStream(fileInput);
byte[] contents = new byte[1024];
int bytesRead = 0;
String strFileContents;
while ((bytesRead = bufferInput.read(contents)) != -1) {
strFileContents = new String(contents, 0, bytesRead);
System.out
.println("The Content of the file read using
BufferedInputStream is:\n"
+ strFileContents);
}
} catch (IOException ioe) {
ioe.printStackTrace();
} finally {
try {
bufferInput.close();
} catch (IOException ioe) {
ioe.printStackTrace();
}
}
}
}
OutputStream Classes:
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Scanner;
/**
* @author Srinivasa Reddy Challa
*
*/
public class FileOutputTest {
urtrainer.java@gmail.com
Java Fundamentals JAVA CSREDDY
/**
* @param args
*/
public static void main(String[] args) {
Scanner scanner = null;
FileOutputStream fileOutput = null;
scanner = new Scanner(System.in);
System.out.println("Enter Name");
String name = scanner.next();
try {
// fileOutput = new FileOutputStream("C:/newFile.txt");
fileOutput = new FileOutputStream("C:/newFile.txt", true);
byte buffer[] = new byte[100];
buffer = name.getBytes();
fileOutput.write(buffer);
System.out
.println("Employee Details Successfully Written
to the file");
}
}
import java.io.BufferedOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Scanner;
/**
* @author training
*
*/
public class FileBufferOutputTest {
/**
* @param args
*/
public static void main(String[] args) {
FileOutputStream fileOutput = null;
BufferedOutputStream bufferOutput = null;
Scanner scanner = null;
urtrainer.java@gmail.com
Java Fundamentals JAVA CSREDDY
scanner = new Scanner(System.in);
System.out.println("Enter Employee Id");
int empId = scanner.nextInt();
System.out.println("Enter Employee Name");
String empName = scanner.next();
String finalValue = "Welcome" + empName + " , Your Employee Id
is "
+ empId;
try {
fileOutput = new FileOutputStream("C:/newFile.txt", true);
bufferOutput = new BufferedOutputStream(fileOutput);
bufferOutput.write(finalValue.getBytes());
System.out.println("Data is Written into the file");
} catch (IOException ioe) {
ioe.printStackTrace();
} finally {
try {
bufferOutput.flush();
bufferOutput.close();
fileOutput.close();
} catch (IOException io) {
io.printStackTrace();
}
}
}
}
import java.io.*;
file.writeBoolean(true); file.writeInt(123456);
file.writeChar('j'); file.writeDouble(1234.56);
file.seek(1); System.out.println(file.readInt());
System.out.println(file.readChar()); System.out.println(file.readDouble());
}}
Character Streams:
urtrainer.java@gmail.com
Java Fundamentals JAVA CSREDDY
Character Streams are those which are transferring 2 bytes at a time between primary
and secondary memory. Character Streams also contain various classes and interfaces
out of which some of them are used for opening a file in read mode and some of them
are used in to open a file in write mode. Character Streams are used in higher level
applications such as internet applications.
Reader Classes:
package CharacterStreams;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
public class FileReaderDemo {
public static void main(String[] args) {
FileReader fileReader = null;
try {
fileReader = new FileReader("C:/data.txt");
int chars;
while ((chars = fileReader.read()) != -1) {
System.out.println((char) chars);
}
} catch (FileNotFoundException fileNotFound) {
fileNotFound.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
try {
fileReader.close();
} catch (IOException ioe) {
ioe.printStackTrace();
}
}
}}
package CharacterStreams;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
public class FileReverseReading {
public static void main(String[] args) {
FileReader fileReader = null;
BufferedReader bufReader = null;
StringBuffer sbuf = new StringBuffer();
File file = new File("c:/data.txt");
try {
fileReader = new FileReader(file);
bufReader = new BufferedReader(fileReader);
int len = (int) file.length();
char[] c = new char[len];
urtrainer.java@gmail.com
Java Fundamentals JAVA CSREDDY
bufReader.read(c, 0, len);
// Reversing the String
char[] cnew = new char[len];
for (int i = 0, j = len - 1; i < len; i++, j--) {
cnew[i] = c[j];
sbuf.append(cnew[i]);
}
System.out.println("The Reversed File Contents is \n"
+ sbuf.toString());
} catch (IOException ioe) {
ioe.printStackTrace();
} finally {
try {fileReader.close();
bufReader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}}
package CharacterStreams;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
public class BufferedReaderDemo {
public static void main(String[] args) {
FileReader fileReader = null;
BufferedReader bufReader = null;
try {fileReader = new FileReader("c:/data.txt");
bufReader = new BufferedReader(fileReader);
String line = null;
System.out.println("The Data which is taken from the file to the
buffer is");
while ((line = bufReader.readLine()) != null) {
System.out.println(line);
}
} catch (FileNotFoundException fileNotFound) {
fileNotFound.printStackTrace();
} catch (IOException ioe) {
ioe.printStackTrace();
} finally {
try {fileReader.close();
bufReader.close();
} catch (IOException ioe) {
ioe.printStackTrace();
}
}}}
Writer Classes:
urtrainer.java@gmail.com
Java Fundamentals JAVA CSREDDY
FileWriter Class:
package CharacterStreams;
import java.io.FileWriter;
import java.io.IOException;
public class FileWriterDemo {
public static void main(String[] args) {
FileWriter fileWriter = null;
String data = "The information to be written to the file ";
try {fileWriter = new FileWriter("C:/info1.txt");
fileWriter.write(data);
System.out.println("The information is written to the file");
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
fileWriter.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}}
BufferedWriter Class:
package CharacterStreams;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
public class BufferedWriterDemo {
public static void main(String[] args) {
BufferedWriter bufferedWriter = null;
FileWriter fileWriter = null;
try {fileWriter = new FileWriter("C:/info1.txt");
bufferedWriter = new BufferedWriter(fileWriter);
bufferedWriter.write("Hello");
bufferedWriter.newLine();
bufferedWriter.write("Welcome");
System.out.println("Information is Written to the file");
Serialization:
When we use normal streams to transfer the data between primary memory and
secondary memory, there is a possibility of performing various read and write operations
which leads to poor performance of an application.
urtrainer.java@gmail.com
Java Fundamentals JAVA CSREDDY
Choose the appropriate package for keeping Serializable sub class and ensure the
package statement must be first statement in java program.
Choose the appropriate class and whose object participating in serialization
process.
Whichever class we are selecting in step 2 that class must implement a predefined
interface called java.io.Serializable – This interface is known as Marked/ Tagged
interface (Marked interface is one which does not contain any abstract methods).
Choose the set of data members which depend on the class.
For each and every data member we must define set of set methods.
For each and every data member we must define set of get methods.
package Serialization;
import java.io.Serializable;
@SuppressWarnings("serial")
public class Student implements Serializable {
int stno; String name; float marks;
public void setStno(int stno) {
this.stno = stno;
}
public void setName(String name) {
this.name = name;
}
public void setMarks(float marks) {
this.marks = marks;
}
public int getStno() {
return stno;
}
public String getName() {
return name;
}
public float getMarks() {
return marks;}}
Developing Serialization Process program:
package Serialization;
urtrainer.java@gmail.com
Java Fundamentals JAVA CSREDDY
import java.io.DataInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
class Spgm {
public static void main(String args[]) {
try { Student so = new Student(); //Step-1
DataInputStream dis = new DataInputStream(System.in);
System.out.println("Enter Student Number:");
String sno = dis.readLine();
int stno = Integer.parseInt(sno);
System.out.println("Enter Student Name:");
String name = dis.readLine();
System.out.println("Enter Student Marks:");
String mark = dis.readLine();
Float marks = Float.parseFloat(mark);
// calling of setmethods Step -2
so.setStno(stno);
so.setName(name);
so.setMarks(marks);
// Choose the file name Step-3
System.out.println("Enter file name to write student data");
String fname = dis.readLine();
FileOutputStream fos = new FileOutputStream(fname);
ObjectOutputStream oos = new ObjectOutputStream(fos); //Step-4
oos.writeObject(so); //Step-5
System.out.println("Student data saved successfully");
fos.close(); //Step-6
oos.close();
} catch (IOException ioe) {
System.out.println("Problem in creating file in write mode");
}
}
}
Deserialization:
The ability to restore a record of a file from secondary memory to primary
memory is known as deserialization.
package Serialization;
urtrainer.java@gmail.com
Java Fundamentals JAVA CSREDDY
import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.ObjectInputStream;
class Dspgm {
public static void main(String args[]) {
try {Student so = new Student(); // 1)
DataInputStream dis = new DataInputStream(System.in);
System.out.println("Enter file name to read Student data:");
String fname = dis.readLine();
FileInputStream fis = new FileInputStream(fname); // 2)
ObjectInputStream ois = new ObjectInputStream(fis); // 3)
Object obj = ois.readObject();
so = (Student) obj; // 4)
System.out.println("Student Number:" + so.getStno()); // 4)
System.out.println("Student Name:" + so.getName());
System.out.println("Student Marks:" + so.getMarks());
fis.close();
ois.close();
} catch (FileNotFoundException ie) {
System.out.println(" Problem in reading the file");
} catch (IOException ie) {
System.out.println("problem in reading the file");
} catch (Exception e) {
System.out.println(e);
}
}
}
Example2:
package Serialization;
import java.io.Serializable;
public class Employee implements Serializable {
long empId;
String empName;
transient long empSalary;
Employee(long empId, String empName, long empSalary) {
this.empId = empId;
this.empName = empName;
this.empSalary = empSalary;
}
public String toString() {
return "Employee [empId=" + empId + ", empName=" + empName
+ ", empSalary=" + empSalary + "]";
}
}
package Serialization;
import java.io.FileInputStream;
import java.io.FileOutputStream;
urtrainer.java@gmail.com
Java Fundamentals JAVA CSREDDY
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
/**
* @author Srinivasa Reddy
*
*/
public class SerializationDemo {
/**
* @param args
*/
public static void main(String[] args) {
try {
Employee emp = new Employee(135234, "SrinivasaReddy", 125000);
System.out.println("Employee Before Serialization" + emp);
FileOutputStream fileOut = new FileOutputStream("c:/data.txt");
// Serialization
ObjectOutputStream oos = new ObjectOutputStream(fileOut);
oos.writeObject(emp);
oos.flush();
oos.close();
} catch (IOException ioe) {
ioe.printStackTrace();
}
try {Employee emp;
FileInputStream fileIn = new FileInputStream("C:/data.txt");
// Deserialization
ObjectInputStream ois = new ObjectInputStream(fileIn);
emp = (Employee) ois.readObject();
ois.close();
System.out.println("Employee After Deserialization" + emp);
} catch (IOException ioe) {
ioe.printStackTrace();
} catch (ClassNotFoundException cnf) {
cnf.printStackTrace();
}
}
}
urtrainer.java@gmail.com
Java Fundamentals JAVA CSREDDY
}
}
Note: Now it is possible to write and execute a java program without using
main function also. After jdk 1.7 it is possible
public class Withoutmain {
static {
System.out.println("Static Block is Executed");
System.exit(0);
}
}
8) Write a program for clone() method in Object class and discuss about its
use?
urtrainer.java@gmail.com
Java Fundamentals JAVA CSREDDY
package CloneExample;
class Student implements Cloneable {
int rollno;
String name;
Student(int rollno, String name) {
this.rollno = rollno;
this.name = name;
}
public Object clone() throws CloneNotSupportedException {
return super.clone();
}
public static void main(String args[]) {
try {
Student s1 = new Student(101, "Srinivasa Reddy");
Student s2 = (Student) s1.clone();
System.out.println(s1.rollno + " " + s1.name);
System.out.println(s2.rollno + " " + s2.name);
} catch (CloneNotSupportedException c) {
c.printStackTrace();
}
}
}
/*
* We want to use the data of one object into another object we are having
two
* possibilities 1) By using copy constructor 2) using clone() method of
object
* class and it return object. What is its importance: Ans If you create
another
* object by using new keyword and assign the values of another object to
this
* one it will require a lot of processing on this object.So to save extra
* processing task we use clone() method and it is very easy to upply.
*/
9) Aggregation Program:
package AggregationExample;
public class Address {
String city, state, country;
public Address(String city, String state, String country) {
super();
this.city = city;
this.state = state;
this.country = country;
}
}
package AggregationExample;
public class Emp {
int id;
urtrainer.java@gmail.com
Java Fundamentals JAVA CSREDDY
String name;
Address address;
public Emp(int id, String name, Address address) {
this.id = id;
this.name = name;
this.address = address;
}
void display() {
System.out.println(id + " " + name);
System.out.println(address.city + " " + address.state + " "
+ address.country);
}
public static void main(String[] args) {
Address address1 = new Address("gzb", "UP", "india");
Address address2 = new Address("gno", "UP", "india");
Emp e = new Emp(111, "varun", address1);
Emp e2 = new Emp(112, "arun", address2);
e.display();
e2.display();
}
}
CaseStudy-1:
import java.io.BufferedReader;
import java.io.InputStreamReader;
interface Inter {
public void input() throws Exception;
public void display();
}
abstract class Sample1 implements Inter {
int i, j;
String[] ename = new String[30];
String[] bname = new String[30];
String[] type = new String[30];
public void input() throws Exception {
BufferedReader br = new BufferedReader(new
InputStreamReader(System.in));
for (int i = 0; i <= 2; i++) {
System.out.println("Enter the name:");
ename[i] = br.readLine();
System.out.println("Enter the bank name:");
bname[i] = br.readLine();
System.out.println("Enter the accnt type:");
type[i] = br.readLine();
}
}
}
CaseStudy-2:
package Case2;
interface Inter {
public void input()throws Exception;
public void display();
}
package Case2;
import java.io.BufferedReader;
import java.io.InputStreamReader;
abstract class Sample1 implements Inter {
int i, j;
String[] ename = new String[30];
String[] bname = new String[30];
String[] type = new String[30];
public void input() throws Exception {
BufferedReader br = new BufferedReader(new
InputStreamReader(System.in));
for (int i = 0; i <= 2; i++) {
System.out.println("Enter the name:");
ename[i] = br.readLine();
System.out.println("Enter the bank name:");
bname[i] = br.readLine();
System.out.println("Enter the accnt type:");
urtrainer.java@gmail.com
Java Fundamentals JAVA CSREDDY
type[i] = br.readLine();
}
}
}
class Sample2 extends Sample1 implements Inter {
public void display() {
System.out.println("name \t bank \t actype");
System.out.println("-----------------------------------");
for (int j = 0; j <= 2; j++) {
System.out.println(ename[j] + "\t" + bname[j] + "\t" +
type[j]);
}
System.out.println("-----------------------------------");
}
}
package Case2;
public class Case22 {
public static void main(String args[])throws Exception
{
/* Sample2 ob1=new Sample2();
ob1.input();
ob1.display(); */
/* Inter i1;
i1=new Sample2();
i1.input();
i1.display(); */
Sample1 s1;
s1=new Sample2();
s1.input();
s1.display();
}
}
Case Study-3:
public interface Inter1 {
public void input() throws Exception;
public void display();
public void area();
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class Square implements Inter1 {
float base;
float height;
double area1;
@Override
public void input() throws Exception {
// TODO Auto-generated method stub
urtrainer.java@gmail.com
Java Fundamentals JAVA CSREDDY
BufferedReader br=new BufferedReader(new
InputStreamReader(System.in));
System.out.println("Enter the Base Value:");
base=Float.parseFloat(br.readLine());
System.out.println("Enter the Height Value:");
height=Float.parseFloat(br.readLine());
}
@Override
public void area() {
// TODO Auto-generated method stub
area1=base*height;
}
@Override
public void display() {
// TODO Auto-generated method stub
System.out.println("Base Value is="+base);
System.out.println("Height Value is="+height);
System.out.println("Square Area is="+area1);
}
}
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class Traingle implements Inter1 {
float base;
float height;
double area1;
@Override
public void input() throws Exception {
// TODO Auto-generated method stub
BufferedReader br=new BufferedReader(new
InputStreamReader(System.in));
System.out.println("Enter the Base Value:");
base=Float.parseFloat(br.readLine());
System.out.println("Enter the Height Value:");
height=Float.parseFloat(br.readLine());
}
@Override
public void area() {
// TODO Auto-generated method stub
area1=base*height/2;
}
@Override
public void display() {
// TODO Auto-generated method stub
System.out.println("Base Value is="+base);
System.out.println("Height Value is="+height);
urtrainer.java@gmail.com
Java Fundamentals JAVA CSREDDY
System.out.println("Traingle Area is="+area1);
}
}
class DemoArea{
public static void main(String args[])throws Exception
{
// Area of Traingle
Inter1 i1;
i1=new Traingle();
i1.input();
i1.area();
i1.display();
// Area of Square or Rectangle
i1=new Square();
i1.input();
i1.area();
i1.display();
}
}
Case Study-4:
package sample;
import java.io.IOException;
public interface IEmployee {
public abstract void input() throws IOException;
public abstract void updateSalary();
public abstract void dispalyDetails();
public static final double HRA = 0.02;
public static final double DA = 0.01;
}
package sample;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class PermanentEmployee implements IEmployee {
String ename[] = new String[5];
String ejob[] = new String[5];
double esal[] = new double[5];
String emno[] = new String[5];
String eloc[] = new String[5];
BufferedReader br = new BufferedReader(new
InputStreamReader(System.in));
public void input() throws IOException {
System.out.println("**********************************");
System.out.println(" Enter Employee Details ");
System.out.println("**********************************");
urtrainer.java@gmail.com
Java Fundamentals JAVA CSREDDY
ename[i] = br.readLine();
System.out.println("Enter Contract Employee Job:");
ejob[i] = br.readLine();
System.out.println("Enter Contract Employee Salary:");
esal[i] = Double.parseDouble(br.readLine());
System.out.println("Enter Contract Employee Mobile Number:");
emno[i] = br.readLine();
System.out.println("Enter Contract Employee Location:");
eloc[i] = br.readLine();
}
}
public void updateSalary() {
for (int i = 0; i < 5; i++) {
esal[i] = esal[i] + (esal[i] * HRA) + (esal[i] * DA);
if (esal[i] < 10000) {
esal[i] = Math.round(esal[i] + 1000);
} else {
esal[i] = Math.round(esal[i] + 500);
}
}
}
public void dispalyDetails() {
for (int i = 0; i < 5; i++) {
System.out.println("**********************************");
System.out.println(" Contract Employee Details Are ");
System.out.println("**********************************");
System.out.println("Employee Name :" + ename[i]);
System.out.println("Employee Job :" + ejob[i]);
System.out.println("Employee Salary :" + esal[i]);
System.out.println("Employee Mobile :" + emno[i]);
System.out.println("Employee Location:" + eloc[i]);
System.out.println("**********************************");
System.out.println("**********************************");
System.out.println();
System.out.println();
}
}
}
package sample;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class HourlyEmployee implements IEmployee {
String ename[] = new String[5];
String ejob[] = new String[5];
double esal[] = new double[5];
String emno[] = new String[5];
String eloc[] = new String[5];
BufferedReader br = new BufferedReader(new
InputStreamReader(System.in));
urtrainer.java@gmail.com
Java Fundamentals JAVA CSREDDY
public void input() throws IOException {
System.out.println("**********************************");
System.out.println(" Enter Hourly Employee Details ");
System.out.println("**********************************");
for (int i = 0; i < 5; i++) {
System.out.println("Enter Hourly Employee Name:");
ename[i] = br.readLine();
System.out.println("Enter Hourly Employee Job:");
ejob[i] = br.readLine();
System.out.println("Enter Hourly Employee Salary:");
esal[i] = Double.parseDouble(br.readLine());
System.out.println("Enter Hourly Employee Mobile Number:");
emno[i] = br.readLine();
System.out.println("Enter Hourly Employee Location:");
eloc[i] = br.readLine();
}
}
public void updateSalary() {
for (int i = 0; i < 5; i++) {
esal[i] = esal[i] + (esal[i] * HRA) + (esal[i] * DA);
if (esal[i] > 8500) {
esal[i] = Math.round(esal[i] + 1000);
} else {
esal[i] = Math.round(esal[i] + 500);
}
}
}
public void dispalyDetails() {
for (int i = 0; i < 5; i++) {
System.out.println("**********************************");
System.out.println(" Hourly Employee Details Are ");
System.out.println("**********************************");
System.out.println("Employee Name :" + ename[i]);
System.out.println("Employee Job :" + ejob[i]);
System.out.println("Employee Salary :" + esal[i]);
System.out.println("Employee Mobile :" + emno[i]);
System.out.println("Employee Location:" + eloc[i]);
System.out.println("**********************************");
System.out.println("**********************************");
System.out.println();
System.out.println();
}
}
}
package sample;
public class EmployeeDemo {
public static void main(String[] args) {
urtrainer.java@gmail.com
Java Fundamentals JAVA CSREDDY
IEmployee i1;
i1 = new PermanentEmployee();
try {
i1.input();
} catch (Exception e) {
System.out.println(e.getMessage());
}
i1.updateSalary();
i1.dispalyDetails();
i1 = new ContractEmployee();
try {
i1.input();
} catch (Exception e) {
System.out.println(e.getMessage());
}
i1.updateSalary();
i1.dispalyDetails();
i1 = new HourlyEmployee();
try {
i1.input();
} catch (Exception e) {
System.out.println(e.getMessage());
}
i1.updateSalary();
i1.dispalyDetails();
}
}
CaseStudy-5:
package Case1;
public interface Inter1 {
public void input()throws Exception;
public void display();
public void insert();
public void update()throws Exception;
public void delete()throws Exception;
}
package Case1;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
urtrainer.java@gmail.com
Java Fundamentals JAVA CSREDDY
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
class Sample1 implements Inter1 {
int eno;
String ename;
String job;
String dept;
int dno;
float sal;
Connection con;
PreparedStatement pst;
String sql;
BufferedReader br;
public void input() throws Exception {
System.out.println("Enter Employee Number:");
eno = Integer.parseInt(br.readLine());
System.out.println("Enter Employee Name:");
ename = br.readLine();
System.out.println("Enter Employee Job:");
job = br.readLine();
System.out.println("Enter Employee Dept:");
dept = br.readLine();
System.out.println("Enter Dept Number:");
dno = Integer.parseInt(br.readLine());
System.out.println("Enter Employee Salary:");
sal = Float.parseFloat(br.readLine());
}
public void display() {
try {
pst = con.prepareStatement("select *from empdemo");
ResultSet rs = pst.executeQuery();
ResultSetMetaData rsmd = rs.getMetaData();
int count = rsmd.getColumnCount();
for (int i = 1; i <= count; i++) {
System.out.print(rsmd.getColumnName(i) + " \t ");
}
System.out.println("\n--------------------------------");
while (rs.next()) {
for (int i = 1; i <= count; i++) {
System.out.print(rs.getString(i) + " \t ");
}
System.out.println("\n-------------------------------");
}
} catch (SQLException e) {
// TODO Auto-generated catch block
System.out.println("Exception in display()");
urtrainer.java@gmail.com
Java Fundamentals JAVA CSREDDY
e.printStackTrace();
}
}
Sample1() throws IOException {
try {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
con = DriverManager.getConnection("jdbc:odbc:mydsn", "training",
"training");
System.out.println("Connection successful");
br = new BufferedReader(new InputStreamReader(System.in));
} catch (SQLException e) {
// TODO Auto-generated catch block
System.out.println("Exception in Constructor()");
e.printStackTrace();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
System.out.println("Exception in Constructor()");
e.printStackTrace();
}
}
public void insert() {
try {
pst = con.prepareStatement("insert into empdemo values(?,?,?,?,?,?)");
pst.setInt(1, eno);
pst.setString(2, ename);
pst.setString(3, job);
pst.setString(4, dept);
pst.setInt(5, dno);
pst.setFloat(6, sal);
pst.executeUpdate();
} catch (SQLException e) {
// TODO Auto-generated catch block
System.out.println("Exception in insert()");
e.printStackTrace();
}
}
/*
* Example For Constructor
* Is it possible to declare a constructor as private ?
urtrainer.java@gmail.com
Java Fundamentals JAVA CSREDDY
* YES YOU CAN
*/
public class Sample {
int a,b;
/*
* Constructor as private
*/
private Sample(int a,int b)
{
this.a=a;
this.b=b;
System.out.println("Private Constructor\n A value:"+a+"\nB value:"+b);
}
public static void main(String args[])
{
System.out.println("Welcome");
/*
* Instatiating the Objects
*/
new Sample(10,20);
new Sample1(30,40);
}
}
class Sample1 {
int a,b;
//private Sample1(int a,int b)
//protected Sample1(int a,int b)
//public Sample1(int a,int b)
Sample1(int a,int b)
{
this.a=a;
this.b=b;
System.out.println("------ Constructor\n A value:"+a+"\nB value:"+b);
}
}
Check the different possibilities for above program..
class Text
{public static void main(String [] args)
{ int x= 0; int y= 0;
for (int z = 0; z < 5; z++)
{ if (( ++x > 2 ) || (++y > 2))
{ x++; }
}
System.out.println(x + " " + y);
}}
// Answer
// 8 2
Some Important Questions:
public class AA {
urtrainer.java@gmail.com
Java Fundamentals JAVA CSREDDY
public static void main(String[] args) {
int i = 9;
switch (i) {
default:
System.out.println("default");
case 0:
System.out.println("zero");
break;
case 1:
System.out.println("one");
case 2:
System.out.println("two");
}
}
}
Output: default
Zero
at c123.main(c123.java:8)
interface interface_1 {
void f1();
}
class Class_1 implements interface_1 {
public void f1() {
System.out.println("From F1 funtion in Class_1 Class");
}
}
public class Demo1 {
public static void main(String args[]) {
Class_1 o11 = new Class_1();
urtrainer.java@gmail.com
Java Fundamentals JAVA CSREDDY
o11.f1();
}
}
Output:
From F1 funtion in Class_1 Class
interface interface_1 {
void f1();
}
class Class_1 implements interface_1 {
void f1() {
System.out.println("From F1 funtion in Class_1 Class");
}
}
public class Demo1 {
public static void main(String args[]) {
Class_1 o11 = new Class_1();
o11.f1();
}
}
at Class_1.f1(Demo1.java:6)
at Demo1.main(Demo1.java:14)
What is the output of the program?
urtrainer.java@gmail.com
Java Fundamentals JAVA CSREDDY
public static void main(String argv[]) {
int i = 10;
Pass p = new Pass();
p.amethod(i);
System.out.println(i);
System.out.println(j);
}
public void amethod(int x) {
x = x * 2;
j = j * 2;
}
}
Output:
10
40
at Pri1.main(Pri1.java:15)
class Base1 {
Base1() {
urtrainer.java@gmail.com
Java Fundamentals JAVA CSREDDY
int i = 100;
System.out.println(i);
}
}
public class Pri1 extends Base1 {
static int i = 200;
public static void main(String argv[]) {
Pri1 p = new Pri1();
System.out.println(i);
int iRand;
iRand = Math.random();
System.out.println(iRand);
}
}
What is the output for this program?
public class Q {
public static void main(String argv[]) {
int anar[] = new int[5];
System.out.println(anar[0]);
}
}
Output: 0
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class demo {
public static void main(String[] args) {
int arr[] = new int[5];
int arr1[] = { 10, 20, 30, 40, 50 };
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
try { for (int i = 0; i < arr1.length; i++) {
System.out.println(arr1[i]);
System.out.println("Enter the Value :");
arr[i] = Integer.parseInt(br.readLine());
} for (int j = 0; j < arr.length; j++)
System.out.println("New Array" + arr[j]);
for (int temp : arr)
System.out.println("Using for each loop:" + arr[temp]);
} catch (Exception e) { System.out.println(e.getMessage()); }
}} Usage for For Each Loop Example:
Write a sample program for counting number of vowels and consonants?
urtrainer.java@gmail.com
Java Fundamentals JAVA CSREDDY
public class Vowel {
public static void main(String[] args) {
String st = args[0];
int j = 0, k = 0;
for (int i = 0; i < st.length(); i++) {
if (st.charAt(i) == 'a' || st.charAt(i) == 'e'
|| st.charAt(i) == 'i' || st.charAt(i) == 'o'
|| st.charAt(i) == 'u') {
j++;
} else
k++;
}
System.out.println("No of vowels " + j);
System.out.println("No of consonants " + k);
}
}
MultiThreading:
A flow of control is known as Thread.
If a Java program contains multiple flow of controls then that java program is
known as Multithreaded program.
The basic aim of Multithreading is to achieve concurrent/simultaneous execution.
The real time implementation of multithreading is to develop real-time servers.
Ex: Tomcat, Web logic, Web sphere
The languages like C/C++ are treated as Single threaded modeling languages
since they contain single flow of control using those languages we can achieve
only sequential execution.
The languages like Java, .Net are treated as Multithreaded modeling languages
since there is a possibility of creating multiple flow of controls.
Multithreading is one of the specialized form of multi tasking of operating systems.
In Java Runtime Environment, if we write any Java Program it is by default
contains 2 types of Threads. They are
1) Fore Ground / Child Thread
2) Back Ground/ Parent Thread
Fore Ground Thread is one which is always executing User-Defined Operations/
Functions.
Back Ground Thread is one which is always monitoring the execution status of fore
ground thread.
By default there exists one fore ground thread and one back ground thread.
Programmatically we can create multiple flow of controls which are nothing but
foreground threads.
In Information Technology we are writing 2 types of applications.
1) Process Based Applications (PBA)
2) Thread Based Applications (TBA)
States of Thread:
urtrainer.java@gmail.com
Java Fundamentals JAVA CSREDDY
When we write any Multi Threading applications there is a possibility of
having Multiple threads and these all threads will undergo various states of a thread.
Thread Contains 5 states. They are 1) new state
2) ready state
3) running state
4) waiting state
5) halted state
new state: A new state is one in which the thread is about to enter into main
memory of the computer
ready: A ready state is one which memory space is allocated for the thread and it is
waiting for the cpu first time
running: A running state is one in which the thread is under the control of cpu or the
thread is under execution. Java environment multiple threads are executing
concurrently by fallowing Round Robin Algorithm of Operating system.
waiting: A state is said to be waiting state if it satisfies any of the fallowing
> Making the thread to sleep for a period of time
> suspending the concurrently executing thread
> joining multiple threads as a single unit
> making the thread to wait for some period of time
Halted:
This state is said to be halted if the thread is reached or finished its execution.
Note:
as long as thread is said to be present in new and halted states their execution states
is false, as long as thread is present in ready, running and waiting states whose
execution status is true.
Number of ways to create a Thread:
urtrainer.java@gmail.com
Java Fundamentals JAVA CSREDDY
In java we have 2 ways to create a thread . they are
1) by using java.lang.Thread class
2) by using java.lang.Runnable interface
By using java.lang.Thread class:
an object of Thread can be created in 3 ways. they are
1) Directly with new operator
Thread t1=new Thread(); // new state
2) Using Factory Method
Thread t2=Thread.currentThread(); // Factory Method
3) Using an object of sub class of Thread class
class th extends Thread
{
//
}
th t1=new th();
Here t1 is an object of the class which in turns an object of Thread class.
Thread class API:
Data Members:
public static final int MIN_PRIORITY(=1)
public static final int NORM_PRIORITY(=5)
public static final int MAX_PRIORITY(=10)
The above said data members are used for setting the priority to the Threads.
Hence they are known as thread Priority Modifiers.
constructors:
1) Thread():
This is used for creating an object of Thread Class without giving name of the
Thread. Ex: Thread t1=new Thread();
2) Thread(String):
This constructor is used for creating an object of Thread class by giving name of
the Thread. Ex: Thread t1=new Thread("java");
3) Thread(Runnable):
This constructor is used for converting Runnable Interface Object into Thread Class
Object. Runnable interface contains only run(), to enter into run() we must make
use of start() and other methods of Thread Class.
Ex: Runnable r=new th(); Thread t1=new Thread(r);
4) Thread(Runnable, String):
urtrainer.java@gmail.com
Java Fundamentals JAVA CSREDDY
This constructor is similar to previous one in functionality but with this constructor we
can give name of the Thread.
Ex: Runnable r=new th();
Thread t1=new Thread(r,"java");
Instance methods:
1) public final void setName(String);
2) public void String getName();
The above methods are used for setting and getting the name to /from the
Thread.
3) public final void setPriority(int);
4) public final int getPriority();
The above methods are used for setting and getting the priority to /from the
Thread.
5) public final void start();
This method is used for bringing the Thread from new state to ready state.
In other words starting the Thread execution when we start the Thread it internally
calls run() of Thread class.
6) public void run();
In this method we must define the logic of the Thread always. In Thread
class, this method is defined with null body. To define our own logic of the Thread,
run() of Thread class must be overridden in derived class by inheriting from Thread
Class.
7) public final boolean isAlive();
This method is used for determining execution status of the Thread. This
method returns true when the Thread is in ready, running and waiting status. This
method returns false when the Thread is in new and halted states.
8) public final void suspend();
This method is used for suspending the currently executing Thread. If the
Thread is suspended, it stops the current execution and it will be entered into waiting
state from running state.
9) public final void resume();
This method is used for bringing the suspended Thread from waiting state to
ready state. When the Thread is resumed it starts executing where it left off
previously.
10) public final void join()throws InterruptedException;
This method is used for joining various fore ground Threads as a single unit.
Static methods:
urtrainer.java@gmail.com
Java Fundamentals JAVA CSREDDY
1) public static final Thread currentThread();
Thread t1=Thread.currentThread();
This method is used for obtaining name of the Threads which are by default
running in Java Environment.
2) public static final void sleep(long)throws InterruptedException;
Thread.sleep(10000);
Here parameter long represents amount of time to be represented interms
of milliseconds (1sec=1000 Millisecond).
This method is used for sending the Thread from running state to waiting
state for a period of time or making the Thread to sleep for some period of time.
Once the sleeping time is completed automatically Thread will be entered to ready
state from waiting state.
Note: If one Thread is sleeping at some address if any other Thread trying to sleep
at the same address then existing Thread will generate InterruptedException.
Sample Program:
public class ThreadDemo {
public static void main(String args[])
{
Thread t1=Thread.currentThread();
System.out.println("Name of the Thread:"+t1);
t1.setName("java");
System.out.println("Name after modified:"+t1);
System.out.println("Status of the Thread1:"+t1.isAlive());
Thread t2=new Thread();
System.out.println("Status of the Thread2:"+t2.isAlive());
System.out.println("Default Name of the Thread2:"+t2.getName());
System.out.println("MIN PRIORITY:"+Thread.MIN_PRIORITY);
System.out.println("MAX PRIORITY:"+Thread.MAX_PRIORITY);
System.out.println("NORM PRIORITY:"+Thread.NORM_PRIORITY);
}
}
Output:
Name of the Thread:Thread[main,5,main]
Name after modified:Thread[java,5,main]
Status of the Thread1:true
Status of the Thread2:false
Default Name of the Thread2:Thread-0
MIN PRIORITY:1
MAX PRIORITY:10
NORM PRIORITY:5
urtrainer.java@gmail.com
Java Fundamentals JAVA CSREDDY
When Threads are in execution the data will be in the above said way.
Each thread has its private run-time stack for storing variables and data.
If two threads execute the same method, each will have its own copy of the stack
to store the method local variables.
The objects instance variables are (Class variables) shared across all the threads,
they are not thread safe.
Stacks
class ThreadEx1 extends Thread {
int i = 0;
ThreadEx1(String name) {
this.setName(name);
}
public void run() {
for (i = 0; i < 5; i++) {
System.out.println("Printing From"+ Thread.currentThread().getName()
+ "The value of i ::"+ i);
try { Thread.sleep(300);
} catch (InterruptedException ex) {
ex.printStackTrace();
}}}}
urtrainer.java@gmail.com
Java Fundamentals JAVA CSREDDY
public class ThreadExMain {
public static void main(String[] args) throws InterruptedException {
Thread t = Thread.currentThread();
System.out.println("The current Thread is" + t.getName());
System.out.println("The Current Thread Priority is" + t.getPriority());
t.setName("myThread");
t.setPriority(6);
System.out.println("The current Thread is" + t.getName());
System.out.println("The Current Thread Priority is" + t.getPriority());
ThreadEx1 ex1 = new ThreadEx1("First");
ThreadEx1 ex2 = new ThreadEx1("Second");
System.out.println("The Thread Priority of ex1 is" + ex1.getPriority());
System.out.println("The Thread Priority of ex2 is" + ex2.getPriority());
ex1.start();
ex2.start();
for (int i = 0; i < 5; i++) {
System.out.println("Printing From:"
+ Thread.currentThread().getName() + "::" + i);
Thread.sleep(100);
}
}
}
Output:
urtrainer.java@gmail.com
Java Fundamentals JAVA CSREDDY
urtrainer.java@gmail.com
Java Fundamentals JAVA CSREDDY
public class ThreadRunnableEx {
public static void main(String[] args) throws InterruptedException {
ThreadRunnableExample r1 = new ThreadRunnableExample();
ThreadRunnableExample r2 = new ThreadRunnableExample();
Thread t1 = new Thread(r1, "First");
Thread t2 = new Thread(r2, "Second");
t1.start();
t2.start();
for (int i = 0; i < 10; i++) {
System.out.println(Thread.currentThread().getName() + "::" + i);
Thread.sleep(100);
}
}
}
Example2:
class ThreadSample implements Runnable {
public Thread t;
public ThreadSample(String nm) {
t = new Thread(this, nm);
t.setName(nm);
}
public void run() {
System.out.println(t.getName());
if (t.getName().equals("First"))
Method1();
if (t.getName().equals("Second"))
Method2();
if (t.getName().equals("Third"))
Method3();
}
public void Method1() {
try {
for (int i = 1; i <= 10; i++) {
System.out.println("Thread Th:" + t.getName() + " " + i);
Thread.sleep(1000);
}
} catch (Exception e) {
System.out.println(e);
}
}
public void Method2() {
try {
for (int i = 1; i <= 10; i++) {
System.out.println("Thread Th:" + t.getName() + " " + i);
Thread.sleep(4000);
}
} catch (Exception e) {
System.out.println(e);
}
}
urtrainer.java@gmail.com
Java Fundamentals JAVA CSREDDY
public void Method3() {
try {
for (int i = 1; i <= 10; i++) {
System.out.println("Thread Th:" + t.getName() + " " + i);
Thread.sleep(5000);
}
} catch (Exception e) {
System.out.println(e);
}
}
}
public class ThreadEx {
public static void main(String[] args) {
ThreadSample T = new ThreadSample("First");
ThreadSample T1 = new ThreadSample("Second");
ThreadSample T2 = new ThreadSample("Third");
T.t.start();
T1.t.start();
T2.t.start();
try {T.t.join();
T1.t.join();
T2.t.join();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}System.out.println("Ok");
}
}
urtrainer.java@gmail.com
Java Fundamentals JAVA CSREDDY
urtrainer.java@gmail.com
Java Fundamentals JAVA CSREDDY
urtrainer.java@gmail.com
Java Fundamentals JAVA CSREDDY
What is Synchronization:
urtrainer.java@gmail.com
Java Fundamentals JAVA CSREDDY
Syntax:
synchronized return_type methodName(List of Parameters if any)
{
Block of stmt(s);
}
Eg: class Account
{ int bal=0;
synchronized void deposit(int amt)
{ bal=bal+amt;
System.out.println(“Current Balance=”+amt);
}
} When one of the Thread is executing deposit(), the account class Object is Locked and
if any other Threads are trying to access deposit() then they made wait by the JVM until
the current Thread completes its execution.
Synchronized static method:
If an ordinary static method is sharable by multiple Threads, then there is a
possibility of generating inconsistent result. To avoid this in consistent result, ordinary
static method definition must be made as Synchronized.
When an ordinary static method is made as synchronized then the corresponding
class will be locked.
Syntax:
synchronized static return_type methodName(List of Parameters if any)
{
Block of stmt(s);
}
Eg: class Account
{ static int bal=0;
Synchronized static void deposit(static int amt)
{ bal=bal+amt;
System.out.println(“Current Balance=”+amt);
}
} if one Thread is executing deposit() then the corresponding class will be locked and at
the same time if any other Threads are trying to access then those Threads must be
made wait until current Thread completes its execution.
urtrainer.java@gmail.com
Java Fundamentals JAVA CSREDDY
Synchronized Blocks:
When we inherit non Synchronized Methods from Base Class or Base Interface into
the derived class, with in the derived class we cannot change the prototype of Base
Class/ Interface methods i.e. Non- Synchronized Methods cannot be made as
Synchronized Methods with in the derived class. Hence, we must use Synchronized
blocks.
Synchronized blocks is an alternative arrangement for Synchronized Methods for
achieving Synchronization technique. Synchronized blocks must be always written with
in the non- Synchronized Method.
synchronized(Object of Current Class)
{
Block of statement(s);
}
Sample Program for Synchronized Method:
class Account {
int bal = 0;
synchronized void deposit(int amt)
// void deposit(int amt)
{
bal = bal + amt;
System.out.println("Current Balance=" + bal);
}
int getBal() {
return bal;
}
}
class Customer extends Thread {
Account ac;
public Customer(Account ac) {
// TODO Auto-generated constructor stub
this.ac = ac;
}
public void run() {
ac.deposit(1000);
}
}
public class SyncDemo1 {
public static void main(String[] args) {
Account ac = new Account();
Customer cu[] = new Customer[5];
for (int i = 0; i < 5; i++) {
cu[i] = new Customer(ac);
}
for (int i = 0; i < 5; i++) {
cu[i].start();
}
urtrainer.java@gmail.com
Java Fundamentals JAVA CSREDDY
try {
for (int i = 0; i < 5; i++) {
cu[i].join();
}
} catch (InterruptedException ie) {
System.out.println("Problem in Thread execution");
}
System.out.println("Total Bal=" + ac.getBal());
}
}
Example Program for Synchronized Blocks:
class Account1 { int bal = 0;
void deposit(int amt) {
synchronized (this) {
bal = bal + amt;
System.out.println("Current Balance=" + bal);
}
}
int getBal() {
return bal;
}
}
class Customer1 extends Thread {
Account1 ac;
public Customer1(Account1 ac) {
// TODO Auto-generated constructor stub
this.ac = ac;
}
public void run() {
ac.deposit(1000);
}
}
public class SyncDemo2 {
public static void main(String[] args) {
Account1 ac = new Account1();
Customer1 cu[] = new Customer1[5];
for (int i = 0; i < 5; i++) {
cu[i] = new Customer1(ac);
}
for (int i = 0; i < 5; i++) {
cu[i].start();
}
try { for (int i = 0; i < 5; i++) {
cu[i].join();
}
} catch (InterruptedException ie) {
System.out.println("Problem in Thread execution");
}
System.out.println("Total Bal=" + ac.getBal());
}}
urtrainer.java@gmail.com
Java Fundamentals JAVA CSREDDY
The process of exchanging the data between Multiple Threads is known as Inter
Thread Communication (or) An output of one Thread is given as an input to some other
Thread. And the output of some other Thread is given as input to some other thread,
then this type of communication is known as Inter Thread Communication.
In order to develop inter thread communication applications we must use some
predefined methods which are present in java.lang.Object
wait(): Is used for making the Thread to wait witout specifying any amount of time.
After that Thread will be entered from waiting stae to ready state.
notify():Is used for bringing the Thread from waiting state to ready state one Thread at
a time.
notifyAll(): Is used for bringing multiple Threads from waiting state to ready state.
urtrainer.java@gmail.com
Java Fundamentals JAVA CSREDDY
class Main
{ int i=1;
synchronized void zig()
{ if(i==1){
System.out.println("Zig");
i=2;
notifyAll();
}
else
{ try{
wait();}
catch(InterruptedException e){}
}
}
synchronized void zag()
{ if(i==2)
{ System.out.println("Zag");
i=3;
notifyAll();
}
else
{ try{
wait();}
catch(InterruptedException e){}
}
}
synchronized void zoom()
{ if (i==3)
{System.out.println("Zoom");
i=1;
notifyAll();
}
else
{ try{
wait();}
catch(InterruptedException e){
}
}
}
}
class P implements Runnable
{ Main M;
Thread t;
P(Main M)
{ this.M=M;
t=new Thread(this,"P");
t.start();
}
urtrainer.java@gmail.com
Java Fundamentals JAVA CSREDDY
urtrainer.java@gmail.com