Java E -Book
Java E -Book
JAVA
SRINIVAS DANDU
AUTHOR PROFILE
Prof. Dandu Srinivas working as an Associate Professor in the Computer Science and
Engineering Department at Narsimha Reddy Engineering College, Hyderabad. He Graduated
in Electronics and Computer Engineering from Sreenidhi Institute of Science and Technology,
and a Master's From JNTU, Hyderabad, India. He is in the Teaching Profession for more than
10 years. He has presented more than 20 papers in National and International Journals and
Conferences. He is a lifetime member of Professional Bodies like ISTE, IAENG, CSI etc.. His
main areas of interest include Artificial Intelligence, Machine Learning, Data Structures, and
Algorithms. D Srinivas is a seasoned software engineer with over a decade of experience in
Java development. He has a passion for teaching and has conducted numerous workshops
and training sessions on Java programming for beginners and advanced learners alike. His
knack for breaking down complex concepts into simple, digestible chunks has earned him
praise from students and colleagues alike. In addition to her professional work, Srinivas is
an avid blogger, where he shares insights,tips, and tutorials on Java programming. His
dedication to making programming accessible to all has garnered a large following in the
developer community."Simple Techniques to Learn Java" is Srinivas’s latest endeavor,
aiming to provide readers with a straightforward and practical approach to mastering Java
programming. Through clear explanations, hands-on examples, and real-world scenarios,
Sarah empowers readers to grasp Java fundamentals and build confidence in their coding
skills
PREFACE
Welcome to "Simple Techniques to Learn Java"! Java has established itself as one of the most
widely used programming languages across various industries. Its versatility, portability, and
robustness make it an
essential skill for both beginners and seasoned developers alike. Whether you're a student
diving into the world of programming or a professional looking to expand your skill set, this
book aims to be your comprehensive guide to mastering Java in the simplest and most
effective way possible.
In this book, we have distilled complex Java concepts into easy-to-understand explanations
and practical examples. We understand that learning programming can sometimes feel
overwhelming, so our goal is to break down barriers and provide you with a clear path to
success. Each chapter is designed to build upon the previous
one, gradually deepening your understanding of Java fundamentals while also introducing
you to advanced techniques. What sets this book apart is its focus on simplicity. We believe
that learning Java doesn't have to be complicated. By presenting the material in a
straightforward manner and providing hands-on exercises, we aim to make your learning
experience both enjoyable and productive. Whether you're learning on your own or with the
guidance of an instructor, this book is your trusted companion on your journey to Java
proficiency. As you embark on this learning adventure, remember that mastering Java is not
just about memorizing syntax or understanding algorithms—it's about embracing a
problem-solving mindset and unleashing your creativity to build innovative solutions. Java
opens the door to endless possibilities in software development, and with dedication and
perseverance, you can harness its power to turn your ideas into reality. We hope this book
serves as a valuable resource in your quest to learn Java and empowers you to explore the
exciting world of programming. So, without further ado, let's dive in and embark on this
rewarding journey together!
Happy coding!
D Srinivas
SYLLABUS
Java Programming
I-INTRODUCTION TO JAVA ESSENTIALS
Introduction Java Essentials, JVM, Java Features, Creation and Execution of Programs, Data
Types, TypeConversion, Casting, Conditional Statements, Loops, Branching Mechanism,Classes,
Objects, ClassDeclaration, Creating Objects, Method Declaration and Invocation,Method
Overloading,
II- CONSTRUCTORS & INHERITANCE
Constructors-ParameterizedConstructors, Constructor Overloading, Cleaning up unused Objects.Class
Variables & Method static Keyword, this Keyword, One Dimensional Arrays, Two-Dimensional Arrays,
Command Line Arguments, Inner Class.
Inheritance: Introduction, Types o f Inheritance, extends Keyword, Examples, Method Overriding,
super,final Keyword, Abstract classes, Interfaces, Abstract Classes Verses Interfaces.
Packages:Creating and Using Packages, Access Protection, Wrapper Classes, String Class,String
BufferClass.
Swing: Introduction, Differences between Swing and AWT, Jframe, Japplet, Jpanel, Components in
Swings, Layout Managers, Jtable, Dialog Box.
Database Handling Using JDBC: Introduction, Types of JDBC Drivers, Load the Driver, Establish
Connection, Create Statement, Execute Query, Iterate Resultset, Scrolla ble Resultset, developing a
JDBCApplication.
Constructors-
2.1 ParameterizedConstructors,
2.2 Constructor Overloading,
2.3 Cleaning up unused Objects.
2.4 Class Variables & Method static Keyword, this Keyword,
2.5 One Dimensional Arrays,
2.6 Two-Dimensional Arrays,
2.7 Command Line Arguments,
2.8 Inner Class.
2.9 Inheritance:
Introduction,
Types o f Inheritance,
2.10 extends Keyword, Examples,
2.11 Method Overriding,
2.12 super,final Keyword,
2.13 Abstract classes,
2.14 Interfaces,
2.15 Abstract Classes Verses
2.16 Interfaces.
2.17 Packages:
D Srinivas, Asst. Professor, CSE
2.18 Creating and Using Packages,
2.19 Access Protection,
2.20 Wrapper Classes,
2.21 String Class,
2,22 String BufferClass.
III-EXCEPTION,MULTITHREADING &INPUT/OUTPUT
I V - A P P L E T S , E V E N T H A N D L I N G & A WT
4.1 Applets:
4.2 Introduction
4.3 Example
4.4 Life Cycle
4.5 Applet Class
4.6 Common Methods Used in Displaying the Output
4.7 Event Handling
4.8 Introduction
4.9 Types of Events, Example.
4.10 AWT
4.11 Introduction
4.12 Components
4.13 Containers
D Srinivas, Asst. Professor, CSE
4.14 Button
4.15 Label
4.16 Checkbox
4.17 Radio Buttons
4.18 Container Class
V - S WI N G S & D A T A B A S E H A N D L I N G U S I N G J D B C
ESSENTIALS OF JAVA:
JVM
JVM (Java Virtual Machine) is an abstract machine. It is called a virtual machine because it doesn't
physically exist. It is a specification that provides a runtime environment in which Java bytecode can
be executed. It can also run those programs which are written in other languages and compiled to
Java bytecode.
1
JVMs are available for many hardware and software platforms. JVM, JRE, and JDK are platform
dependent because the configuration of each OS is different from each other. However, Java
isplatform independent. There are three notions of the JVM: specification, implementation,
andinstance.
The JVM performs the following main tasks:
Loads code
Verifies code
Executes code
Provides runtime environment
JRE
JRE is an acronym for Java Runtime Environment. It is also written as Java RTE. The Java
Runtime Environment is a set of software tools which are used for developing Java applications. It
is used to provide the runtime environment. It is the implementation of JVM. It physically exists. It
contains a set of libraries + other files that JVM uses at runtime.
The implementation of JVM is also actively released by other companies besides Sun
MicroSystems.
JDK
JDK
JDK is an acronym for Java Development Kit. The Java Development Kit (JDK) is a software
development environment which is used to develop Java applications and applets. It physically
exists. It contains JRE + development tools.
JDK is an implementation of any one of the below given Java Platforms released by OracleCorporation:
• Standard Edition Java Platform
• Enterprise Edition Java Platform
• Micro Edition Java Platform
The JDK contains a private Java Virtual Machine (JVM) and a few other resources such as an
interpreter/loader (java), a compiler (javac), an archiver (jar), a documentation generator (Javadoc),
etc. to complete the development of a Java Application .
2
CREATION AND EXECUTION OF PROGRAMS:
Step 1 : Creation of a Java program :-
By creating of a Java program we mean of writing of a Java program on any editor or IDE. This
includes modifying of the program on editor, even after program has been written once. Creation of
a Java program is not limit to only write program on editor and then leave it. Generally, creating of
a Java program means writing a program on a editor or IDE, making all the corrections needed and
then saving the program on secondary storage device as hard drive. After creating a Java program
you should provide .java extension to file. It signifies that the particular file is a Java source code.
Our next step after creation of program is the compilation of Java program. Generally Java program
which we have created in step 1 with a .java extension, it is been compiled by the compiler. Suppose
if we take example of our program say WelcomeJavaPrograms.java, when we want to compile this
we use command such as javac.
3
Step 4: Bytecode Verification by JVM :-
In order to maintain security of the program JVM has bytecode verifier. After the classes are loaded
in to memory , bytecode verifier comes into picture and verifies bytecode of the loaded class in
order to maintain security. It check whether bytecodes are valid. Thus it prevent our computer from
malicious viruses and worms.
4
Example:
Saving
c:\java\labs\Demo.java
Compiling
javac Demo.java
Running
java Demo
DATATYPES:
Data types specify the different sizes and values that can be stored in the variable. There are two
types of data types in Java:
1. Primitive data types: The primitive data types include boolean, char, byte, short, int, long, float
and double.
2. Non-primitive data types: The non-primitive data types include Classes, Interfaces, and Arrays.
5
There are eight primitive data types in Java:
The Boolean data type is used to store only two possible values: true and false.
This data type is used for simple flags that track true/false conditions.
The Boolean data type specifies one bit of information, but its "size" can't be defined
precisely.
The float data type is a single-precision 32-bit IEEE 754 floating point.
Its value range is unlimited.
It is recommended to use a float (instead of double) if you need to save memory in large
arrays of floating point numbers.
The float data type should never be used for precise values, such as currency.
Its default value is 0.0F.
The double data type is a double-precision 64-bit IEEE 754 floating point.
7
Its value range is unlimited.
The double data type is generally used for decimal values just like float.
The double data type also should never be used for precise values, such as currency.
Its default value is 0.0d.
Non-primitive data types are called reference types because they refer to objects.
The main difference between primitive and non-primitive data types are:
Primitive types are predefined (already defined) in Java. Non-primitive types are created by
the programmer and is not defined by Java (except for String).
Non-primitive types can be used to call methods to perform certain operations, while
primitive types cannot.
A primitive type has always a value, while non-primitive types can be null.
A primitive type starts with a lowercase letter, while non-primitive types starts with an
uppercase letter.
The size of a primitive type depends on the data type, while non-primitive types have all the
same size.
Converting one primitive datatype into another is known as type casting (type conversion) in Java.
You can cast the primitive datatypes in two ways namely, Widening and, Narrowing.
1. Implicite or Widening − Converting a lower datatype to a higher datatype is known as
widening. In this case the casting/conversion is done automatically therefore, it is known as
implicit type casting. In this case both datatypes should be compatible with each other.
8
2. Explicite or Narrowing − Converting a higher datatype to a lower datatype is known as
narrowing. In this case the casting/conversion is not done automatically, you need to convert
explicitly using the cast operator “( )” explicitly. Therefore, it is known as explicit type
casting. In this case both datatypes need not be compatible with each other.
CONDITIONAL STATEMENTS:
Conditional statements are:
1. if statement
2. if-else statement
3. nested if statement
4. if-else-if statement
5. Switch Case Statement
1. if statement:
The if statement is the most basic of all the control flow statements. The if statement tells our
program to execute a certain section of code only if a particular test evaluates to true.
Syntax:
if(condition){ Statement
(s);
}
2. if-else statement:
If a condition is true then the section of code under if would execute else the section
of code under else would execute.
Syntax:
if(condition)
{ Statement(s);
9
}
else {
Statement(s);
}
3.Nested if statement:
An if statement inside another the statement. If the outer if condition is true then the
section of code under outer if condition would execute and it goes to the inner if
condition. If inner if condition is true then the section of code under inner if
condition would execute.
Syntax:
if(condition_1)
{ Statement1(s);
if(condition_2)
{Statement2(s);
}
4. if-else-if statement
If a condition is true then the section of code under if would execute else the section
of code under else would execute. Otherwise check the other condition. It will
continue until condition true else it execute else statements.
Syntax:
if(condition)
{ Statement(s);
else if(condition) {
10
Statement(s);
else if(condition)
{Statement(s);
else{
Statement(s);
5. Switch Case:
The switch statement in Java is a multi branch statement. We use this in Java when we
have multiple options to select. It executes particular option based on the value of an
expression.
Switch works with the byte, short, char, and int primitive data types. It also works
with enumerated types, the String class, and a few special classes that wrap certain
primitive types such as Character, Byte, Short, and Integer.
Syntax:
switch(expression)
{case valueOne:
//statement(s
break;
case valueTwo:
//statement(s
break;
default: //optional
//statement(s) //This code will be executed if all cases are not matched
11
}
LOOPS:
1. While Loop
The while loop loops through a block of code as long as a specified condition is true:
Syntax
while (condition) {
// code block to be executed
}
2. For Loop
When you know exactly how many times you want to loop through a block of code, use
the for loop instead of a while loop:
Syntax
Statement 1 is executed (one time) before the execution of the code block.
Statement 3 is executed (every time) after the code block has been executed
The do/while loop is a variant of the while loop. This loop will execute the code block once,
before checking if the condition is true, then it will repeat the loop as long as the condition is true.
Syntax
do {
he loop will always be executed at least once, even if the condition is false, because the code block is
executed before the condition is tested:
BRANCHING STATEMENTS:
Branching statements are the statements used to jump the flow of execution from one part of a
program to another. The branching statements are mostly used inside the control statements. Java
has mainly three branching statements, i.e., continue, break, and return. The branching
statements allow us to exit from a control statement when a certain condition meet.
In Java, continue and break statements are two essential branching statements used with the control
statements. The break statement breaks or terminates the loop and transfers the control outside theloop.
The continue statement skips the current execution and pass the control to the start of the loop.
The return statement returns a value from a method and this process will be done explicitly.
break Statement
The labeled and unlabeled break statement are the two forms of break statement in Java. The break
statement is used for terminating a loop based on a certain condition.
13
continue Statement
The continue statement is another branching statement used to immediately jump to the next
iteration of the loop. It is a special type of loop which breaks current iteration when the condition
is met and start the loop with the next iteration. In simple words, it continues the current flow of
the program and stop executing the remaining code at the specified condition.
Syntax
control-flow-statement;
continue;
return Statement
The return statement is also a branching statement, which allows us to explicitly return value from a
method. The return statement exits us from the calling method and passes the control flow to
where the calling method is invoked. Just like the break statement, the return statement also has twoforms,
i.e., one that passes some value with control flow and one that doesn't.
Syntax
return value;
Or,
return;
CLASSES/OBJECTS
Java is an object-oriented programming language.
Everything in Java is associated with classes and objects, along with its attributes and methods. For
example: in real life, a car is an object. The car has attributes, such as weight and color,
and methods, such as drive and brake.
Create a Class
Main.java
In Java, an object is created from a class. We have already created the class named MyClass, so now
we can use this to create objects.
To create an object of MyClass, specify the class name, followed by the object name, and use the
keyword new:
Example
{int x = 5;
System.out.println(myObj.x);
METHOD DECLARATION:
A Java method is a collection of statements that are grouped together to perform an operation. When
you call the System.out.println() method, for example, the system actually executes several statements
in order to display a message on the console.
Creating Method
Considering the following example to explain the syntax of a method −
Syntax
public static int methodName(int a, int b) {
// body
15
}
Here,
public static − modifier
int − return type
methodName − name of the method
a, b − formal parameters
int a, int b − list of parameters
Method definition consists of a method header and a method body. The same is shown in the
following syntax −
Syntax
modifier returnType nameOfMethod (Parameter List) {
// method body
}
The syntax shown above includes −
modifier − It defines the access type of the method and it is optional to use.
returnType − Method may return a value.
nameOfMethod − This is the method name. The method signature consists of the method name and
the parameter list.
Parameter List − The list of parameters, it is the type, order, and number of parameters of a method.
These are optional, method may contain zero parameters.
method body − The method body defines what the method does with the statements.
METHOD OVERLOADING:
When a class has two or more methods by the same name but different parameters, it is known as
method overloading. It is different from overriding. In overriding, a method has the same method
name, type, number of parameters, etc.
Syntax:
void func() { ... }
16
void func(int a) { ... }
float func(double a) { ... }
float func(int a, float b) { ... }
Example:
class MethodOverloading
{ private static void
display(int
a) { System.out.println("Arguments: " + a);
}
private static void display(int a, int
b) { System.out.println("Arguments: " + a + " and " + b);
}
public static void main(String[] args)
{display(1);
display(1, 4);
}
}
METHOD INVOCATION:
The Java programming language provides two basic kinds of methods: instance methods and class (or
static) methods. The difference between these two kinds of methods is:
Instance methods require an instance before they can be invoked; whereas class methods do not.
Instance methods use dynamic (late) binding, whereas class methods use static (early) binding.
When the Java virtual machine invokes a class method, it selects the method to invoke based on the
type of the object reference, which is always known at compile-time. On the other hand, when the
virtual machine invokes an instance method, it selects the method to invoke based on the actual class
of the object, which may only be known at run time.
The JVM uses two different instructions, shown in the following table, to invoke these two different
kinds of methods: invoke virtual for instance methods, and invoke static for class methods.
17
UNIT-II
CONSTRUCTORS:
In Java, a constructor is a block of codes similar to the method. It is called when an instance of the
class is created. At the time of calling constructor, memory for the object is allocated in the
memory.
It is a special type of method which is used to initialize the object. Every time an object is created
using the new() keyword, at least one constructor is called.
A constructor in Java is a special method that is used to initialize objects. The constructor is called
when an object of a class is created. It can be used to set initial values for object attributes:
Note that the constructor name must match the class name, and it cannot have a return type (like
void). Also note that the constructor is called when the object is created.
All classes have constructors by default: if you do not create a class constructor yourself, Java
creates one for you. However, then you are not able to set initial values for object attributes.
TYPES OF CONSTRUCTORS:
a) Default Constructor
A constructor is called "Default Constructor" when it doesn't have any parameter.
18
Example of default constructor
class Student{
//creating a default constructor
Output:
Student(){System.out.println("Welcome to java");}
//main method Welcome to java
public static void main(String args[]){
//calling a default constructor
Student b=new Student();
}
}
b) Parameterized Constructor
19
The parameterized constructor is used to provide different values to distinct objects. However, you
can provide the same values also.
class Student4
{
int id;
String name;
//creating a parameterized constructor
Student4(int i,String n)
{
id = i;
name = n; Output:
} 10 Abc
//method to display the values 20 Xyz
void display()
{
System.out.println(id+" "+name);
}
public static void main(String args[])
{
//creating objects and passing values
Student4 s1 = new Student4(10,"Abc");
Student4 s2 = new Student4(20,"Xyz");
//calling method to display the values of object
s1.display();
s2.display();
}
}
CONSTRUCTOR OVERLOADING:
In Java, a constructor is just like a method but without return type. It can also be overloaded like
Java methods.
Constructor overloading in Java is a technique of having more than one constructor with different
parameter lists. They are arranged in a way that each constructor performs a different task. They
are differentiated by the compiler by the number of parameters in the list and their types.
The constructor name must be same as the The method name may or may not be same
class name. as the class name.
21
A constructor is used to initialize the state A method is used to expose the behavior of
of an object. an object.
Copy Constructor
There is no copy constructor in Java. However, we can copy the values from one object to another
like copy constructor in C++.
There are many ways to copy the values of one object into another in Java. They are:
By constructor
By assigning the values of one object into another
By clone() method of Object class
The Java runtime environment deletes objects when it determines that they are no longer beingused.
This process is known as garbage collection.
An object is eligible for garbage collection when there are no more references to that object.
References that are held in a variable are naturally dropped when the variable goes out of scope. Or
you can explicitly drop an object reference by setting the value of a variable whose data type is a
reference type to null.
Garbage Collection is process of reclaiming the runtime unused memory automatically. In other
words, it is a way to destroy the unused objects.
CLASS VARIABLES:
Declared inside the class definition (but outside any of the instance methods). They are not tied to
any particular object of the class, hence shared across all the objects of the class. Modifying a class
variable affects all objects instance at the same time.
Class variables − Class variables also known as static variables are declared with the static
keyword in a class, but outside a method, constructor or a block. There would only be one
copy of each class variable per class, regardless of how many objects are created from it.
Instance variables − Instance variables are declared in a class, but outside a method. When
space is allocated for an object in the heap, a slot for each instance variable value is created.
Instance variables hold values that must be referenced by more than one method,
constructor or block, or essential parts of an object's state that must be present throughout
the class.
Local variables − Local variables are declared in methods, constructors, or blocks. Local
variables are created when the method, constructor or block is entered and the variable will
be destroyed once it exits the method, constructor, or block.
CLASS METHODS:
You learned from the Java Methods chapter that methods are declared within a class, and that they
are used to perform certain actions:
23
Example
STATIC KEYWORD:
The static keyword in Java is used for memory management mainly. We can apply static keyword
with variables, methods, blocks and nested classes. The static keyword belongs to the class than an
instance of the class.
he static variable can be used to refer to the common property of all objects (which is not
unique for each object), for example, the company name of employees, college name of
students, etc.
The static variable gets memory only once in the class area at the time of class loading.
24
Advantages of static variable
class
Student{ int
rollno;
String name;
String college="VDC";
}
If you apply static keyword with any method, it is known as static method.
A static method belongs to the class rather than the object of a class.
A static method can be invoked without the need for creating an instance of a class.
A static method can access static data member and can change the value of it.
class
Student{ int
rollno;
String name;
static String college = "VDC";
//static method to change the value of static variable
static void change(){
college = "VDC";
}
THIS KEYWORD:
There can be a lot of usage of java this keyword. In java, this is a reference variable that refers to
the current object.
The this keyword can be used to refer current class instance variable. If there is ambiguity between
the instance variables and parameters, this keyword resolves the problem of ambiguity.
You may invoke the method of the current class by using the this keyword. If you don't use the
this keyword, compiler automatically adds this keyword while invoking the method.
The this() constructor call can be used to invoke the current class constructor. It is used to reuse
the constructor. In other words, it is used for constructor chaining.
26
4) this: to pass as an argument in the method
The this keyword can also be passed as an argument in the method. It is mainly used in the event
handling.
We can pass the this keyword in the constructor also. It is useful if we have to use one object in
multiple classes.
We can return this keyword as an statement from the method. In such case, return type of the
method must be the class type (non-primitive).
ARRAYS:
Java array is an object which contains elements of a similar data type. Additionally, The elements
of an array are stored in a contiguous memory location. It is a data structure where we store similar
elements. We can store only a fixed set of elements in a Java array.
Array in Java is index-based, the first element of the array is stored at the 0th index, 2nd element is
stored on 1st index and so on.
In Java, array is an object of a dynamically generated class. Java array inherits the Object class, and
implements the Serializable as well as Cloneable interfaces. We can store primitive values or
objects in an array in Java. Like C/C++, we can also create single dimentional or
multidimentional arrays in Java.
Moreover, Java provides the feature of anonymous arrays which is not available in C/C++.
Advantages
Code Optimization: It makes the code optimized, we can retrieve or sort the data
efficiently.
Random access: We can get any data located at an index position.
27
Disadvantages
Size Limit: We can store only the fixed size of elements in the array. It doesn't grow its size
at runtime. To solve this problem, collection framework is used in Java which grows
automatically.
class Testarray1{
public static void main(String
args[]){int a[]={33,3,4,5
for(int i=0;i<a.length;i++)
System.out.println(a[i]);
Two – dimensional array is the simplest form of a multidimensional array. A two – dimensional
array can be seen as an array of one – dimensional array for easier understanding.
Declaration – Syntax:
data_type[][] array_name = new data_type[x][y];
For example: int[][] arr = new int[10][20];
Initialization–Syntax:
array_name[row_index][column_index] = value;
For example: arr[0][0] = 1;
28
Syntax:
data_type[1st dimension][2nd dimension][]..[Nth dimension] array_name = new
data_type[size1][size2]….[sizeN];
where:
data_type: Type of data to be stored in the array. For example: int, char, etc.
class GFG {
public static void main(String[] args)
{
A command-line argument is an information that directly follows the program's name on the
command line when it is executed. To access the command-line arguments inside a Java program is
quite easy. They are stored as strings in the String array passed to main( ).
Example
The following program displays all of the command-line arguments that it is called with -
29
INNER CLASSES:
Java inner class or nested class is a class which is declared inside the class or interface.
We use inner classes to logically group classes and interfaces in one place so that it can be more
readable and maintainable.
Additionally, it can access all the members of outer class including private data members and
methods.
1. class Java_Outer_class{
2. //code
3. class Java_Inner_class{
4. //code
5. }
There are basically three advantages of inner classes in java. They are as follows:
1) Nested classes represent a special type of relationship that is it can access all the members (data
members and methods) of outer class including private.
2) Nested classes are used to develop more readable and maintainable code because it logically
group classes and interfaces in one place only.
INHERITANCE :
Inheritance in Java is a mechanism in which one object acquires all the properties and behaviors of
a parent object. Inheritance represents the IS-A relationship which is also known as a parent-child
relationship.
Advantages:
For Method Overriding (so runtime polymorphism can be achieved).
For Code Reusability.
1) Single Inheritance
Single inheritance is damn easy to understand. When a class extends another one class only then
we call it a single inheritance. The below flow diagram shows that class B extends only one class
which is A. Here A is a parent class of B and B would be a child class of A.
Class Parent
{
public void display()
{
System.out.println("Parent class method");
}
}
2) Multilevel Inheritance
Multilevel inheritance refers to a mechanism in Object Oriented technology where one can inherit
from a derived class, thereby making this derived class the base class for the new class. As you can
see in below flow diagram C is subclass or child class of B and B is a child class of A.
Class GrandParent
{
public void method1()
{
System.out.println("Class GrandParent method");
}
}
Class Parent extends GrandParent
{
public void method2()
{
System.out.println("class Parent method");
}
32
}
Class Child extends Parent
{
public void method3()
{
System.out.println("class Child method");
}
public static void main(String args[])
{
Child obj = new Child();
obj.method1(); //calling grand parent class method
obj.method2(); //calling parent class method
obj.method3(); //calling local method
}
}
3) Hierarchical Inheritance
In such kind of inheritance one class is inherited by many sub classes. In below example class B,C
and D inherits the same class A. A is parent class (or base class) of B,C & D.
4) Multiple Inheritance
“Multiple Inheritance” refers to the concept of one class extending (Or inherits) more than one
base class. The inheritance we learnt earlier had the concept of one base class or parent. The
problem with “multiple inheritance” is that the derived class will have to manage the dependency
on two base classes.
34
Note 1: Multiple Inheritance is very rarely used in software projects. Using Multiple inheritance
often leads to problems in the hierarchy. This results in unwanted complexity when further
extending the class.
Note 2: Most of the new OO languages like Small Talk, Java, C# do not support Multiple
inheritance. Multiple Inheritance is supported in C++.
5) Hybrid Inheritance
In simple terms you can say that Hybrid inheritance is a combination of Single and Multiple
inheritance. A typical flow diagram would look like below. A hybrid inheritance can be achieved in
the java in a same way as multiple inheritance can be!! Using interfaces. yes you heard it right. By
using interfaces you can have multiple as well as hybrid inheritance in Java.
class C
{
public void disp()
{
System.out.println("C");
}
}
class A extends C
{
public void disp()
{
System.out.println("A");
}
}
class B extends C
{
35
public void disp()
{
System.out.println("B");
}
}
class D extends A
{
public void disp()
{
System.out.println("D");
}
public static void main(String args[]){
METHOD OVERRIDING :
If subclass (child class) has the same method as declared in the parent class, it is known as method
overriding in Java.
1. The method must have the same name as in the parent class
2. The method must have the same parameter as in the parent class.
3. There must be an IS-A relationship (inheritance).
class Vehicle{
//defining a method
void run(){System.out.println("Vehicle is running");}
}
//Creating a child class
36
class Bike2 extends Vehicle{
//defining the same method as in the parent class
void run(){System.out.println("Bike is running safely");}
public static void main(String args[]){
Bike2 obj = new Bike2();//creating object
obj.run();//calling method
}
SUPER KEYWORD :
The super keyword in Java is a reference variable which is used to refer immediate parent class
object.
Whenever you create the instance of subclass, an instance of parent class is created implicitly which
is referred by super reference variable.
super keyword to access the data member or field of parent class. It is used if parent class and child
class have same fields.
class Animal{
String color="white";
}
class Dog extends
Animal{String
color="black";
void
printColor(){ System.out.println(color);//prints
color of Dog class
System.out.println(super.color);//prints color of Animal class
}
}
class TestSuper1{
public static void main(String
args[]){Dog d=new Dog();
37
d.printColor();
}}
2) super can be used to invoke parent class method
The super keyword can also be used to invoke parent class method. It should be used if subclass
contains the same method as parent class. In other words, it is used if method is overridden.
c lass Animal{
void eat(){System.out.println("eating...");}
}
class Dog extends Animal{
void eat(){System.out.println("eating bread...");}
void bark(){System.out.println("barking...");}
void work(){
super.eat();
bark();
}
}
class TestSuper2{
public static void main(String
args[]){Dog d=new Dog();
d.work();
}}
The super keyword can also be used to invoke the parent class constructor.
class Animal{
Animal(){System.out.println("animal is created");}
}
class Dog extends
Animal{Dog(){
super();
System.out.println("dog is created");
}
}
class TestSuper3{
public static void main(String
args[]){Dog d=new Dog();
}}
38
FINAL KEYWORD:
The final keyword in java is used to restrict the user. The java final keyword can be used in many
context. Final can be:
1. variable
2. method
3. class
If you make any variable as final, you cannot change the value of final variable(It will be constant).
There is a final variable speedlimit, we are going to change the value of this variable, but It can't be
changed because final variable once assigned a value can never be changed.
class Bike9{
final int speedlimit=90;//final variable
void run(){
speedlimit=400;
}
public static void main(String
args[]){Bike9 obj=new Bike9();
obj.run();
}
}
ABSTRACT CLASS:
A class which is declared with the abstract keyword is known as an abstract class in Java. It can
have abstract and non-abstract methods (method with the body).
Abstraction
Abstraction is a process of hiding the implementation details and showing only functionality to the
user.
A class which is declared as abstract is known as an abstract class. It can have abstract and non-
abstract methods. It needs to be extended and its method implemented. It cannot be instantiated.
40
Abstract Method in Java
A method which is declared as abstract and does not have implementation is known as an abstract
method.
In this example, Bike is an abstract class that contains only one abstract method run. Its
implementation is provided by the Honda class.
abstract class
Bike{ abstract void
run();
}
class Honda4 extends Bike{
void run(){System.out.println("running safely");}
public static void main(String args[]){
Bike obj = new Honda4();
obj.run();
}
}
Abstract class having constructor, data member and methods
An abstract class can have a data member, abstract method, method body (non-abstract method),
constructor, and even main() method.
abstract class
Bike{ Bike(){System.out.println("bike is
created");}abstract void run();
void changeGear(){System.out.println("gear changed");}
}
//Creating a Child class which inherits Abstract class
class Honda extends Bike{
void run(){System.out.println("running safely..");}
}
//Creating a Test class which calls abstract and non-abstract methods
class TestAbstraction2{
public static void main(String
args[]){Bike obj = new Honda();
41
obj.run();
obj.changeGear();
}
}
INTERFACE:
An interface in Java is a blueprint of a class. It has static constants and abstract methods.
The interface in Java is a mechanism to achieve abstraction. There can be only abstract methods in the
Java interface, not method body. It is used to achieve abstraction and multiple inheritances in Java.
Since Java 8, we can have default and static methods in an interface. Since Java 9, we can have
private methods in an interface.
n interface is declared by using the interface keyword. It provides total abstraction; means all the
methods in an interface are declared with the empty body, and all the fields are public, static and
final by default. A class that implements an interface must implement all the methods declared in
the interface.
Syntax:
interface <interface_name>{
// declare constant fields
// declare methods that abstract
// by default.
}
The relationship between classes and interfaces
As shown in the figure given below, a class extends another class, an interface extends another
interface, but a class implements an interface.
42
Interface Example
In this example, the Printable interface has only one method, and its implementation is provided in
the A6 class.
interface
printable{void
print();
}
class A6 implements printable{
public void print(){System.out.println("Hello");}
public static void main(String args[]){
A6 obj = new A6();
obj.print();
}
}
44
public static void main(String
args[]){A7 obj = new A7();
obj.print();
obj.show();
}
}
Difference between abstract class and interface
Abstract class and interface both are used to achieve abstraction where we can declare the abstract
methods. Abstract class and interface both can't be instantiated.
But there are many differences between abstract class and interface that are given below.
1) Abstract class can have abstract and non- Interface can have only abstract methods. Since
abstract methods. Java 8, it can have default and static methods also.
4) Abstract class can provide the Interface can't provide the implementation of
implementation of interface. abstract class.
6) An abstract class can extend another Java An interface can extend another Java interface
class and implement multiple Java interfaces. only.
7) An abstract class can be extended using An interface can be implemented using keyword
keyword "extends". "implements".
45
9)Example: Example:
public abstract class public interface
Shape{public abstract void Drawable{void draw();
draw(); }
}
PACKAGES:
A package is a collection of similar types of Java entities such as classes, interfaces, subclasses,
exceptions, errors, and enums. A package can also contain sub-packages.
Advantages:
Java provides a large number of classes grouped into different packages based on a particular
functionality.
46
Examples:
java.lang: It contains classes for primitive types, strings, math functions, threads, and exceptions.
java.util: It contains classes such as vectors, hash tables, dates, Calendars, etc.
2. User-defined packages
As the name suggests, these packages are defined by the user. We create a directory whose name
should be the same as the name of the package. Then we create a class inside the directory.
Creating a Package
Java supports a keyword called “package” which is used to create user-defined packages in java
programming. It has the following general form:
package packageName;
For example:
package myPackage;
public class A {
// class body
47
Compiling a Package
If you are using an IDE (Integrated Development Environment), then for compiling the package,
The syntax:
javac -d . Example.java
You need to use a fully qualified name e.g. com.srinivad.MyClass etc to run the class.
To Compile:
javac -d . MyClass.java
To run:
java com.srinivas.MyClass
Package Import
import keyword which is used to access package and its classes into the java program.
There are 3 different ways to refer to any class that is present in a different package:
Packages in Java add another dimension to access control. Both classes and packages are a means of
data encapsulation. While packages act as containers for classes and other subordinate packages,
classes act as containers for data and code. Because of this interplay between packages and classes,
Java packages addresses four categories of visibility for class members:
The table below gives a real picture of which type access is possible and which is not when using
packages in Java:
WRAPPER CLASSES:
A Wrapper class is a class which contains the primitive data types (int, char, short, byte, etc). In
other words, wrapper classes provide a way to use primitive data types (int, char, short, byte, etc) as
objects. These wrapper classes come under java.util package.
The wrapper class in Java provides the mechanism to convert primitive into object and object into
primitive.
boolean Boolean
char Character
byte Byte
short Short
int Integer
long Long
float Float
49
double Double
a) Autoboxing
The automatic conversion of primitive data type into its corresponding wrapper class is known as
autoboxing,
public class AutoBoxingTest {
}
}
Output
10 10
B) Unboxing
The automatic conversion of wrapper type into its corresponding primitive type is known as
unboxing.
Output
10 10
50
STRING CLASS:
String is a sequence of characters. But in Java, string is an object that represents a sequence of
characters. The java.lang.String class is used to create a string object.
For Example:
String s="welcome";
B) By new keyword
JVM will create a new string object in normal (non-pool) heap memory, and the literal
"Welcome" will be placed in the string constant pool. The variable s will refer to the object in a
heap (non-pool).
String class provides a lot of methods to perform operations on strings such as compare(),
concat(), equals(), split(), length(), replace(), compareTo(), intern(), substring() etc.
StringBuffer class is used to create mutable (modifiable) string. The StringBuffer class in java is
same as String class except it is mutable i.e. it can be changed.
A string that can be modified or changed is known as mutable string. StringBuffer and
StringBuilder classes are used for creating mutable string.
The append() method concatenates the given argument with this string.
lass StringBufferExample{
}
51
}
class
StringBufferExample2{ public
static void main(String
");
System.out.println(sb);//prints HJavaello
3) StringBuffer replace() method
The replace() method replaces the given string from the specified beginIndex and endIndex.
class
StringBufferExample3{ public
sb.replace(1,3,"Java");
System.out.println(sb);//prints HJavalo
}
4)
} StringBuffer delete() method
cTlhaessdSelteritne(g)Bm
ufefethrEodxaomf pSlter4in{ gBuffer class deletes the string from the specified beginIndex to
endIndex.
public static void main(String
sb.delete(1,3);
System.out.println(sb);//prints Hlo
52
}
}
5) StringBuffer reverse() method
class
StringBufferExample5{ public
static void main(String
sb.reverse();
System.out.println(sb);//prints olleH
53
UNIT-III
EXCEPTION:
Types of Exceptions
There are mainly two types of exceptions: checked and unchecked. Here, an error is considered as
the unchecked exception. According to Oracle, there are three types of exceptions:
1. Checked Exception
2. Unchecked Exception
3. Error
1) Checked Exception
The classes which directly inherit Throwable class except RuntimeException and Error are known as
checked exceptions
e.g. IOException, SQLException etc.
Checked exceptions are checked at compile-time.
2) Unchecked Exception
The classes which inherit RuntimeException are known as unchecked exceptions
e.g. ArithmeticException, NullPointerException, ArrayIndexOutOfBoundsException etc.
Unchecked exceptions are not checked at compile-time, but they are checked at runtime.
3) Error
54
Exception Handling
The core advantage of exception handling is to maintain the normal flow of the application. An
exception normally disrupts the normal flow of the application that is why we use exception
handling.
Exception Keywords
Keyword Description
The "try" keyword is used to specify a block where we should place exception code. The
try
try block must be followed by either catch or finally. It means, we can't use try block alone.
The "catch" block is used to handle the exception. It must be preceded by try block which
catch
means we can't use catch block alone. It can be followed by finally block later.
The "finally" block is used to execute the important code of the program. It is executed
finally
whether an exception is handled or not.
55
throw The "throw" keyword is used to throw an exception.
a) try block
Java try block is used to enclose the code that might throw an exception. It must be used within the
method.
If an exception occurs at the particular statement of try block, the rest of the block code will not
execute. So, it is recommended not to keeping the code in try block that will not throw an exception.
1. try{
2. //code that may throw an exception
3. }catch(Exception_class_Name ref){}
1. try{
2. //code that may throw an exception
3. }finally{}
b) catch block
Java catch block is used to handle the Exception by declaring the type of exception within the
parameter. The declared exception must be the parent class exception ( i.e., Exception) or the
generated exception type. However, the good approach is to declare the generated type of exception.
The catch block must be used after the try block only. You can use multiple catch block with a
single try block.
Example:
Output:
java.lang.ArithmeticException: / by zero
Multi-catch block
A try block can be followed by one or more catch blocks. Each catch block must contain a different
exception handler. So, if you have to perform different tasks at the occurrence of different
exceptions, use java multi-catch block.
At a time only one exception occurs and at a time only one catch block is executed.
All catch blocks must be ordered from most specific to most general, i.e. catch for
ArithmeticException must come before catch for Exception.
c) finally block
Java finally block is a block that is used to execute important code such as closing connection, stream etc.
Java finally block is always executed whether exception is handled or not. Java finally block follows
try or catch block.
Example:
class TestFinallyBlock{
public static void main(String
args[]){try{
int data=25/5;
System.out.println(data);
}
catch(NullPointerException e){System.out.println(e);}
finally{System.out.println("finally block is always executed");}
System.out.println("rest of the code...");
}
}
57
d) throw keyword
throw exception;
e) throws keyword
The Java throws keyword is used to declare an exception. It gives an information to the programmer
that there may occur an exception so it is better for the programmer to provide the exception
handling code so that normal flow can be maintained.
Exception Handling is mainly used to handle the checked exceptions. If there occurs any unchecked
exception such as NullPointerException, it is programmers fault that he is not performing check up
before the code being used.
Syntax of throws
There are many differences between throw and throws keywords. A list of differences between throw
and throws are given below:
Java throw keyword is used to explicitly Java throws keyword is used to declare an
1)
throw an exception. exception.
58
Checked exception cannot be propagated Checked exception can be propagated with
2)
using throw only. throws.
4) Throw is used within the method. Throws is used with the method signature.
User Defined Exception or custom exception is creating your own exception class and throws that
exception using ‘throw’ keyword. This can be done by extending the class Exception.
The help of custom exception, you can have your own exception and message.
Output:
Exception occured: InvalidAgeException:not valid
rest of the code...
59
MULTITHREADING:
However, we use multithreading than multiprocessing because threads use a shared memory area.
They don't allocate separate memory area so saves memory, and context-switching between the
threads takes less time than process.
1) It doesn't block the user because threads are independent and you can perform multiple
operations at the same time.
3) Threads are independent, so it doesn't affect other threads if an exception occurs in a single
thread.
THREAD CLASS:
Thread class provide constructors and methods to create and perform operations on a thread.Thread
class extends Object class and implements Runnable interface.
Commonly used Constructors of Thread class:
o Thread()
o Thread(String name)
o Thread(Runnable r)
o Thread(Runnable r,String name)
RUNNABLE INTERFACE:
The Runnable interface should be implemented by any class whose instances are intended to be
executed by a thread. Runnable interface have only one method named run().
1. public void run(): is used to perform action for a thread.
Starting a thread:
start() method of Thread class is used to start a newly created thread. It performs following tasks:
o A new thread starts(with new callstack).
o The thread moves from New state to the Runnable state.
o When the thread gets a chance to execute, its target run() method will run.
A thread can be in one of the five states. According to sun, there is only 4 states in thread life cycle
in java new, runnable, non-runnable and terminated. There is no running state.
But for better understanding the threads, we are explaining it in the 5 states.
The life cycle of the thread in java is controlled by JVM. The java thread states are as follows:
1. New
2. Runnable
3. Running
4. Non-Runnable (Blocked)
5. Terminated
Each thread have a priority. Priorities are represented by a number between 1 and 10. In most cases,
thread schedular schedules the threads according to their priority (known as preemptive scheduling).
But it is not guaranteed because it depends on JVM specification that which scheduling it chooses.
3 constants defined in Thread class:
1. public static int MIN_PRIORITY
2. public static int NORM_PRIORITY
3. public static int MAX_PRIORITY
SYNCHRONIZATION:
class Customer{
int amount=10000;
synchronized void withdraw(int
amount){ System.out.println("going to
withdraw...");if(this.amount<amount){
System.out.println("Less balance; waiting for deposit...");
try{ wait()
;
}
catch(Exception e){}
}
this.amount-=amount; System.out.println("withdraw completed...");
}
synchronized void deposit(int
amount){ System.out.println("going to
deposit..."); this.amount+=amount;
System.out.println("deposit completed... ");
notify();
}
}
class Test{
public static void main(String args[]){
63
final Customer c=new Customer();
new Thread(){
public void
run(){ c.withdraw(15
000);
}
}
start();
new Thread(){
public void
run(){ c.deposit(10
000);}
}
start();
}}
Output:
going to withdraw...
Less balance; waiting for deposit... going to deposit...
deposit completed... withdraw completed
Java provides strong but flexible support for I/O related to files and networks but this tutorial
covers very basic functionality related to streams and I/O. We will see the most commonly used
examples one by one −
Byte Streams
Java byte streams are used to perform input and output of 8-bit bytes. Though there are many
classes related to byte streams but the most frequently used classes are, FileInputStream and
FileOutputStream. Following is an example which makes use of these two classes to copy an input
file into an output file −
Example
import java.io.*;
public class CopyFile {
64
public static void main(String args[]) throws IOException { FileInputStream in = null;
65
FileOutputStream out = null; try
{in = new FileInputStream("input.txt");
out = new FileOutputStream("output.txt"); int c;
while ((c = in.read()) != -1) {
out.write(c);
}
}finally {
if (in != null) {
in.close();
}
if (out != null) { out.close();
}} }}
Now let's have a file input.txt with the following content −
This is test for copy file.
As a next step, compile the above program and execute it, which will result in creating output.txt file
with the same content as we have in input.txt. So let's put the above code in CopyFile.java file and
do the following −
$javac CopyFile.java
$java CopyFile
Character Streams
Java Byte streams are used to perform input and output of 8-bit bytes, whereas Java Character
streams are used to perform input and output for 16-bit unicode. Though there are many classes
related to character streams but the most frequently used classes are, FileReader and FileWriter.
Though internally FileReader uses FileInputStream and FileWriter uses FileOutputStream but here
the major difference is that FileReader reads two bytes at a time and FileWriter writes two bytes at a
time.
We can re-write the above example, which makes the use of these two classes to copy an input
file (having unicode characters) into an output file −
Example
import java.io.*;
public class CopyFile {
public static void main(String args[]) throws IOException
{FileReader in = null; FileWriter out = null; try
{in = new FileReader("input.txt");
out = new FileWriter("output.txt");
int c;
while ((c = in.read()) != -1)
{out.write(c);
}
}
finally {
if (in != null)
{
66
in.close();
}
if (out != null)
{out.close();
}
} }}
Now let's have a file input.txt with the following content −
This is test for copy file.
As a next step, compile the above program and execute it, which will result in creating output.txt file
with the same content as we have in input.txt. So let's put the above code in CopyFile.java file and
do the following −
$javac CopyFile.java
$java CopyFile
Standard Streams
All the programming languages provide support for standard I/O where the user's program can take
input from a keyboard and then produce an output on the computer screen. Java provides the
following three standard streams −
Standard Input − This is used to feed the data to user's program and usually a keyboard is used as
standard input stream and represented asSystem.in.
Standard Output − This is used to output the data produced by the user's program and usually a
computer screen is used for standard output stream and represented as System.out.
Standard Error − This is used to output the error data produced by the user's program and
usually a computer screen is used for standard error stream and represented as System.err.
Following is a simple program, which creates InputStreamReader to read standard input stream until
the user types a "
Example
import java.io.*;
public class ReadConsole {
public static void main(String args[]) throws IOException
{InputStreamReader cin = null;try {
cin = new InputStreamReader(System.in);
System.out.println("Enter characters, 'q' to quit.");
charc;
do {
c = (char) cin.read();
System.out.print(c);
} while(c != 'q');
}
finally {
if (cin != null) {
67
cin.close();
} } }}
This program continues to read and output the same character until we press 'q' −
$javac ReadConsole.java
$java ReadConsole
Enter characters, 'q' to quit. 1
1
eeqq
Reading and Writing Files
As described earlier, a stream can be defined as a sequence of data. The InputStream is used to read
data from a source and the OutputStream is used for writing data to a destination.
Here is a hierarchy of classes to deal with Input and Output streams.
The two important streams are FileInputStream and FileOutputStream
FileInputStream
This stream is used for reading data from the files. Objects can be created using the keyword new
and there are several types of constructors available.
Following constructor takes a file name as a string to create an input stream object to read the
file −
InputStream f = new FileInputStream("C:/java/hello");
Following constructor takes a file object to create an input stream object to read the file. First we
create a file object using File() method as follows −
File f = new File("C:/java/hello"); InputStream f = new FileInputStream(f);
Once you have InputStream object in hand, then there is a list of helper methods which can be used to
read to stream or to do other operations on the stream.
ByteArrayInputStream
DataInputStream
SCANNER CLASS:
Scanner class in Java is found in the java.util package. Java provides various ways to read input from
the keyboard, the java.util.Scanner class is one of them.
The Java Scanner class breaks the input into tokens using a delimiter which is whitespace by default.
It provides many methods to read and parse various primitive values.
The Java Scanner class is widely used to parse text for strings and primitive types using a regular
expression. It is the simplest way to get input in Java. By the help of Scanner in Java, we can get
input from the user in primitive types such as int, long, double, byte, float, short, etc. To get the
instance of Java Scanner which reads input from the user, we need to pass the input stream
(System.in) in the constructor of Scanner class. For Example:
To get the instance of Java Scanner which parses the strings, we need to pass the strings in the
constructor of Scanner class. For Example:
69
Example
import java.util.*;
public class ScannerExample {
public static void main(String
args[]){Scanner in = new
Scanner(System.in);
System.out.print("Enter your name: ");
String name = in.nextLine();
Output:
Enter your name: sonoo jaiswal
Name is: sonoo jaiswal
70
Input Types
In the example above, we used the nextLine() method, which is used to read Strings. To read other
types, look at the table below:
Method Description
In the example below, we use different methods to read data of various types:
Example
import java.util.Scanner;
class Main {
public static void main(String[] args) {
Scanner myObj = new Scanner(System.in);
// String input
String name = myObj.nextLine();
// Numerical input
int age = myObj.nextInt();
71
double salary = myObj.nextDouble();
Java BufferedInputStream class is used to read information from stream. It internally uses buffer
mechanism to make the performance fast.
When the bytes from the stream are skipped or read, the internal buffer automatically refilled
from the contained input stream, many bytes at a time.
When a BufferedInputStream is created, an internal buffer array is created.
public class BufferedInputStream extends FilterInputStream
Constructor Description
It creates the BufferedInputStream and saves it argument,
BufferedInputStream(InputStream IS)
the input stream IS, for later use.
BufferedInputStream(InputStream IS, It creates the BufferedInputStream with a specified buffer
int size) size and saves it argument, the input stream IS, for later use.
Let's see the simple example to read data of file using BufferedInputStream:
package com.javatpoint;
import java.io.*;
public class
BufferedInputStreamExample{public static
void main(String args[]){ try{
FileInputStream fin=new FileInputStream("D:\\testout.txt");
BufferedInputStream bin=new BufferedInputStream(fin);
int i;
while((i=bin.read())!=-
1){System.out.print((char)
i);
72
}
bin.close();
fin.close();
}catch(Exception e){System.out.println(e);}
}
}
Here, we are assuming that you have following data in "testout.txt" file:
javaTpoint
Java BufferedOutputStream class is used for buffering an output stream. It internally uses buffer to
store data. It adds more efficiency than to write data directly into a stream. So, it makes the
performance fast.
For adding the buffer in an OutputStream, use the BufferedOutputStream class. Let's see the syntax
for adding the buffer in an OutputStream:
Constructor Description
It creates the new buffered output stream which is used
BufferedOutputStream(OutputStream os)
for writing the data to the specified output stream.
It creates the new buffered output stream which is used
BufferedOutputStream(OutputStream os,
for writing the data to the specified output stream with a
int size)
specified buffer size.
73
2 RandomAccessFile(File file, String mode)
This creates a random access file stream to read from, and optionally to write to, a
file with the specified name.
Methodsinherited
This class inherits methods from the following classes −
Java.io.Object
75
UNIT-IV
APPLETS:
Applet is a special type of program that is embedded in the webpage to generate the dynamic
content. It runs inside the browser and works at client side.
Advantage of Applet
There are many advantages of applet. They are as follows:
o It works at client side so less response time.
o Secured
o It can be executed by browsers running under many plateforms, including Linux, Windows, Mac
Os etc.
Drawback of Applet
o Plugin is required at client browser to execute applet.
APPLET CLASS:
java.applet.Applet class
For creating any applet java.applet.Applet class must be inherited. It provides 4 life cycle methods
of applet.
1. public void init(): is used to initialized the Applet. It is invoked only once.
2. public void start(): is invoked after the init() method or browser is maximized. It is used
to start the Applet.
76
3. public void stop(): is used to stop the Applet. It is invoked when Applet is stop or
browser is minimized.
4. public void destroy(): is used to destroy the Applet. It is invoked only once.
java.awt.Component class
The Component class provides 1 life cycle method of applet.
1. public void paint(Graphics g): is used to paint the Applet. It provides Graphics class
object that can be used for drawing oval, rectangle, arc etc.
Simple example of Applet by html file:
To execute the applet by html file, create an applet and compile it. After that create an html file
and place the applet code in html file. Now click the html file.
1. //First.java
import java.applet.Applet;
import java.awt.Graphics;
public class First extends
Applet{ public void paint(Graphics
g){ g.drawString("welcome",150,15
0);
}
}
Simple example of Applet by appletviewer tool:
To execute the applet by appletviewer tool, create an applet that contains applet tag in comment
and compile it. After that run it by: appletviewer First.java. Now Html file is not required but it is
for testing purpose only.
1. //First.java
import java.applet.Applet;
import java.awt.Graphics;
public class First extends
Applet{public void
paint(Graphics g){
g.drawString("welcome to applet",150,150);
}
/*
<applet code="First.class" width="300" height="300">
</applet>
*/
To execute the applet by appletviewer tool, write in command prompt:
Difference between Applet and Application programming
c:\>javac First.java
c:\>appletviewer First.java
77
Parameter in Applet
We can get any information from the HTML file as a parameter. For this purpose, Applet class
provides a method named getParameter().
Syntax:
public String getParameter(String parameterName)
78
myapplet.html
1. <html>
2. <body>
3. <applet code="UseParam.class" width="300" height="300">
4. <param name="msg" value="Welcome to applet">
5. </applet>
6. </body>
7. </html>
EVENT HANDLING:
TYPES OF EVENT:
The events can be broadly classified into two categories:
Foreground Events - Those events which require the direct interaction of user.They are
generated as consequences of a person interacting with the graphical components in Graphical User
Interface. For example, clicking on a button, moving the mouse, entering a character through
keyboard,selecting an item from list, scrolling the page etc.
Background Events - Those events that require the interaction of end user are known as
background events. Operating system interrupts, hardware or software failure, timer expires, an
operation completion are the example of background events.
Event Handling
Event Handling is the mechanism that controls the event and decides what should happen if an
event occurs. This mechanism have the code which is known as event handler that is executed
when an event occurs. Java Uses the Delegation Event Model to handle the events. This model
defines the standard mechanism to generate and handle the events.Let's have a brief introduction to
this model.
The Delegation Event Model has the following key participants namely:
Source - The source is an object on which event occurs. Source is responsible for providing
information of the occurred event to it's handler. Java provide as with classes for source object.
Listener - It is also known as event handler. Listener is responsible for generating response to an
event. From java implementation point of view the listener is also an object. Listener waits until it
receives an event. Once the event is received , the listener process the event an then returns.
79
EVENT CLASSES AND LISTENER INTERFACES:
Applets are displayed in a window and they use the AWT to perform input and output functions.
To output a string to an applet, use drawString( ), which is a member of the Graphics class.
Typically, it is called from within either update() or paint( ). It has the following general form:
Here, message is the string to be output beginning at x, y. In a java window, the upper-left corner is
location 0, 0. The drawString( ) method will not recognize newline characters. If we want to start
a line of text on another line, we must do it manually, specifying the X,Y location where we want
the line to begin.
To set the background color of an applet’s window, we use setBackground( ). To set the
foreground color, we use setForeground(). These methods are defined by Component, and have
the general forms:
Here, newColor specifies the new color. The class Color defines the following values that can be
used to specify colors:
80
For example, this sets the background color to blue and the text color to yellow:
setBackground(Color.blue);
setForeground(Color.yellow);
We can change these colors as and when required during the execution of the applet. The default
foreground color is black. The default background color is light gray. We can obtain the current
settings for the background and foreground colors by calling getBackground( ) and
getForeground( ), respectively. They are also defined by Component and bear the general form:
Color getBackground()
Color getForeground()
The example below shows a simple applet to change the color of the foreground and background.
import java.awt.*;
import java.applet.*;
/* <applet code="Applet_Prog" width=500 height=550> </applet>*/
public class Applet_Prog extends Applet
{
public void paint (Graphics g)
{
setBackground(Color.BLUE);
setForeground(Color.RED);
g.drawString("Using Colors in An Applet" , 100,250);
}
}
AWT:
Java AWT (Abstract Window Toolkit) is an API to develop GUI or window-based applications in java.
Java AWT components are platform-dependent i.e. components are displayed according to the
view of operating system. AWT is heavyweight i.e. its components are using the resources of OS.
The java.awt package provides classes for AWT api such as TextField, Label, TextArea,
RadioButton, CheckBox, Choice, List etc.
81
JAVA AWT HIERARCHY:
The hierarchy of Java AWT classes are given below.
Container:
The Container is a component in AWT that can contain another components like buttons,
textfields, labels etc. The classes that extends Container class are known as container such as
Frame, Dialog and Panel.
Window
The window is the container that have no borders and menu bars. You must use frame, dialog or
another window for creating a window.
Panel
The Panel is the container that doesn't contain title bar and menu bars. It can have other
components like button, textfield etc.
Frame
The Frame is the container that contain title bar and can have menu bars. It can have other
components like button, textfield etc.
Method Description
public void add(Component c) inserts a component on this component.
public void setSize(int width,int height) sets the size (width and height) of the
component.
public void setLayout(LayoutManager m) defines the layout manager for the
component.
public void setVisible(boolean status) changes the visibility of the component, by
default false.
82
Java AWT Example
To create simple awt example, you need a frame. There are two ways to create a frame in AWT.
o By extending Frame class (inheritance)
o By creating the object of Frame class (association)
AWT Example by Inheritance
Let's see a simple example of AWT where we are inheriting Frame class. Here, we are showing
Button component on the Frame.
import java.awt.*;
class First extends
Frame{ First(){ Button b=new
Button("click me");
b.setBounds(30,100,80,30);// setting button position
add(b);//adding button into frame
setSize(300,300);//frame size 300 width and 300 height
setLayout(null);//no layout manager
setVisible(true);//now frame will be visible, by default not visible
}
public static void main(String args[]){ First f=new First();
}}
The setBounds(int xaxis, int yaxis, int width, int height) method is used in the above example that
sets the position of the awt button.
83
UNIT-V
JAVA SWING :
Java Swing tutorial is a part of Java Foundation Classes (JFC) that is used to create window- based
applications. It is built on the top of AWT (Abstract Windowing Toolkit) API and entirely written
in java.
Unlike AWT, Java Swing provides platform-independent and lightweight components.
The javax.swing package provides classes for java swing API such as JButton, JTextField,
JTextArea, JRadioButton, JCheckbox, JMenu, JColorChooser etc.
Method Description
public void add(Component c) add a component on another component.
public void setSize(int width,int height) sets size of the component.
public void setLayout(LayoutManager m) sets the layout manager for the component.
public void setVisible(boolean b) sets the visibility of the component. It is by
default false.
84
Hierarchy of Java Swing classes
The hierarchy of java swing API is given below.
We can write the code of swing inside the main(), constructor or any other method.
Simple Java Swing Example
Let's see a simple swing example where we are creating one button and adding it on the JFrame
object inside the main() method.
import javax.swing.*;
public class FirstSwingExample
{ public static void main(String[] args)
{
JFrame f=new JFrame();//creating instance of JFrame
JButton b=new JButton("click");//creating instance of JButton
b.setBounds(130,100,100, 40);//x axis, y axis, width, height
f.add(b);//adding button in JFrame
f.setSize(400,500);//400 width and 500 height
f.setLayout(null);//using no layout managers f.setVisible(true);//making the frame visible
}}
85
CONTAINERS:
Jframe
The javax.swing.JFrame class is a type of container which inherits the java.awt.Frame class. JFrame
works like the main window where components like labels, buttons, textfields are added to create a
GUI.
Unlike Frame, JFrame has the option to hide or close the window with the help of
setDefaultCloseOperation(int) method.
JFrame Example
import java.awt.FlowLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.Jpanel;
public class JFrameExample {
public static void main(String s[]) {
JFrame frame = new JFrame("JFrame Example");
JPanel panel = new JPanel();
panel.setLayout(new FlowLayout());
JLabel label = new JLabel("JFrame By Example");
JButton button = new JButton(); button.setText("Button");
panel.add(label);
panel.add(button);
frame.add(panel);
frame.setSize(200, 300);
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
Japplet
As we prefer Swing to AWT. Now we can use JApplet that can have all the controls of swing. The
JApplet class extends the Applet class.
Example of EventHandling in JApplet:
86
import java.applet.*; import javax.swing.*; import java.awt.event.*;
In the above example, we have created all the controls in init() method because it is invoked only
once.
myapplet.html
1. <html>
2. <body>
3. <applet code="EventJApplet.class" width="300" height="300">
</applet>
</body>
</html>
JDialog
The JDialog control represents a top level window with a border and a title used to take some
form of input from the user. It inherits the Dialog class.
Unlike JFrame, it doesn't have maximize and minimize buttons.
JDialog class declaration
Let's see the declaration for javax.swing.JDialog class.
1. public class JDialog extends Dialog implements WindowConstants, Accessible, RootPaneConta
iner
Commonly used Constructors:
Constructor Description
JDialog() It is used to create a modeless dialog without
a title and without a specified Frame owner.
87
JDialog(Frame owner) It is used to create a modeless dialog with
specified Frame as its owner and an empty
title.
JDialog(Frame owner, String title, boolean It is used to create a dialog with the specified
modal) title, owner Frame and modality
88
JPanel
The JPanel is a simplest container class. It provides space in which an application can attach any
other component. It inherits the JComponents class.
It doesn't have title bar.
89
Overview of some Swing Components Java JButton
The JButton class is used to create a labeled button that has platform independent implementation.
The application result in some action when the button is pushed. It inherits AbstractButton class.
JLabel
The object of JLabel class is a component for placing text in a container. It is used to display a
single line of read only text. The text can be changed by an application but a user cannot edit it
directly. It inherits JComponent class.
JLabel class declaration
Let's see the declaration for javax.swing.JLabel class.
1. public class JLabel extends JComponent implements SwingConstants, Accessible
Commonly used Constructors:
Constructor Description
JLabel() Creates a JLabel instance with no image and
with an empty string for the title.
JLabel(String s) Creates a JLabel instance with the specified
text.
JLabel(Icon i) Creates a JLabel instance with the specified
image.
90
JLabel(String s, Icon i ,int Creates a JLabel instance with the sp
horizontalAlignment)
Commonly used Methods:
Methods Description
String getText() t returns the text string that a label displays.
void setText(String text) It defines the single line of text this
component will display.
void setHorizontalAlignment(int alignment) It sets the alignment of the label's contents
along the X axis.
Icon getIcon() It returns the graphic image that the label
displays.
int getHorizontalAlignment() It returns the alignment of the label's contents
along the X axis.
91
JTextField
The object of a JTextField class is a text component that allows the editing of a single line text. It
inherits JTextComponent class.
JTextArea
The object of a JTextArea class is a multi line region that displays text. It allows the editing of
multiple line text. It inherits JTextComponent class
92
JTextArea class declaration
Let's see the declaration for javax.swing.JTextArea class.
public class JTextArea extends JTextComponent Java JTextArea Example
import javax.swing.*;
public class TextAreaExample
{
TextAreaExample(){ JFr
ame f= new JFrame();
JTextArea area=new JTextArea("Welcome to javatpoint");
area.setBounds(10,30, 200,200);
f.add(area);
f.setSize(300,300);
f.setLayout(null);
f.setVisible(true);
}
public static void main(String args[])
{
new TextAreaExample();
}}
93
LAYOUT MANAGEMENT
LayoutManagers
The LayoutManagers are used to arrange components in a particular manner. LayoutManager is an
interface that is implemented by all the classes of layout managers.
BorderLayout
The BorderLayout provides five constants for each region:
1. public static final int NORTH
2. public static final int SOUTH
3. public static final int EAST
4. public static final int WEST
5. public static final int CENTER
Output:
Java GridLayout
The GridLayout is used to arrange the components in rectangular grid. One component is
displayed in each rectangle.
Constructors of GridLayout class
1. GridLayout(): creates a grid layout with one column per component in a row.
2. GridLayout(int rows, int columns): creates a grid layout with the given rows and columns but
no gaps between the components.
3. GridLayout(int rows, int columns, int hgap, int vgap): creates a grid layout with the given rows
and columns alongwith given horizontal and vertical gaps.
}
public static void main(String[] args)
{new MyGridLayout(); }}
Java FlowLayout
The FlowLayout is used to arrange the components in a line, one after another (in a flow). It is the
default layout of applet or panel.
Fields of FlowLayout class
96
1. public static final int LEFT
2. public static final int RIGHT
3. public static final int CENTER
4. public static final int LEADING
5. public static final int TRAILING
Constructors of FlowLayout class
1. FlowLayout(): creates a flow layout with centered alignment and a default 5 unit horizontal and
vertical gap.
2. FlowLayout(int align): creates a flow layout with the given alignment and a default 5 unit
horizontal and vertical gap.
3. FlowLayout(int align, int hgap, int vgap): creates a flow layout with the given alignment and the
given horizontal and vertical gap.
}
public static void main(String[] args)
{new MyFlowLayout();
}}
97
DATABASE HANDLING USING JDBC:
Connceting to DB
What is JDBCDriver?
JDBC drivers implement the defined interfaces in the JDBC API, for interacting with your
database server.
For example, using JDBC drivers enable you to open database connections and to interact with it
by sending SQL or database commands then receiving results with Java.
The Java.sql package that ships with JDK, contains various classes with their behaviours defined and
their actual implementaions are done in third-party drivers. Third party vendors implements the
java.sql.Driver interface in their database driver.
98
The JDBC-ODBC Bridge that comes with JDK 1.2 is a good example of this kind of driver
99
You can think of the application server as a JDBC "proxy," meaning that it makes calls for theclient
application. As a result, you need some knowledge of the application server's configurationin order
to effectively use this driver type.
Your application server might use a Type 1, 2, or 4 driver to communicate with the database,
understanding the nuances will prove helpful.
In a Type 4 driver, a pure Java-based driver communicates directly with the vendor's database
through socket connection. This is the highest performance driver available for the database and is
usually provided by the vendor itself.
This kind of driver is extremely flexible, you don't need to install special software on the client or
server. Further, these drivers can be downloaded dynamically.
100
MySQL's Connector/J driver is a Type 4 driver. Because of the proprietary nature of their
network protocols, database vendors usually supply type 4 drivers.
Let's first create a table in the mysql database, but before creating table, we need to create database
first.
1. create database sonoo;
2. use sonoo;
3. create table emp(id int(10),name varchar(40),age int(3));
In this example, sonoo is the database name, root is the username and password.
import java.sql.*;
class MysqlCon{
public static void main(String args[]){
try{ Class.forName("com.mysql.jdbc.Driver");
Connection
con=DriverManager.getConnection( "jdbc:mysql://local
host:3306/sonoo","root","root");
//here sonoo is database name, root is username and password
}}
102
Let's first create a table in the mysql database, but before creating table, we need to create database
first.
1. create database sonoo;
2. use sonoo;
3. create table emp(id int(10),name varchar(40),age int(3)); Example to Connect Java Application
with mysql database
In this example, sonoo is the database name, root is the username and password.
import java.sql.*;
class MysqlCon{
public static void main(String
args[]){ try{ Class.forName("com.mysql.jd
bc.Driver");
Connection
con=DriverManager.getConnection( "jdbc:mysql://localhost:3306/sonoo","root
","root"); //here sonoo is database name,root is username and password
}
}
A ResultSet object maintains a cursor that points to the current row in the result set. The term
"result set" refers to the row and column data contained in a ResultSet object.
The methods of the ResultSet interface can be broken down into three categories −
Navigational methods: Used to move the cursor around.
Get methods: Used to view the data in the columns of the current row being pointed by the
cursor.
Update methods: Used to update the data in the columns of the current row. The updates can
then be updated in the underlying database as well.
The cursor is movable based on the properties of the ResultSet. These properties are designated
when the corresponding Statement that generates the ResultSet is created.
JDBC provides the following connection methods to create statements with desired ResultSet −
createStatement(int RSType, int RSConcurrency);
prepareStatement(String SQL, int RSType, int RSConcurrency);
The first argument indicates the type of a ResultSet object and the second argument is one of two
ResultSet constants for specifying whether a result set is read-only or updatable.
Type of ResultSet
The possible RSType are given below. If you do not specify any ResultSet type, you will
automatically get one that is TYPE_FORWARD_ONLY.
103
Type Description
ResultSet.TYPE_FORWARD_ONLY The cursor can only move forward in the
result set.
ResultSet.TYPE_SCROLL_INSENSITI The cursor can scroll forward and
VE backward, and the result set is not sensitive
to changes made by others to the database
that occur after the result set was created.
The cursor can scroll forward and
backward, and the result set is sensitive to
ResultSet.TYPE_SCROLL_SENSITIVE. changes made by others to the database that
occur after the result set was created.
Concurrencyof ResultSet
The possible RSConcurrency are given below. If you do not specify any Concurrency type, you
will automatically get one that is CONCUR_READ_ONLY.
Concurrency Description
ResultSet.CONCUR_READ_ONLY Creates a read-only result set. This is the
default
ResultSet.CONCUR_UPDATABLE Creates an updateable result set.
The cursor can scroll forward and backward, and the result set is sensitive to changes made by
others to the database that occur after the result set was created.
ResultSet.TYPE_SCROLL_SENSITIVE.
Viewinga Result Set
The ResultSet interface contains dozens of methods for getting the data of the current row. There
is a get method for each of the possible data types, and each get method has two versions
One that takes in a column name.
One that takes in a column index.
For example, if the column you are interested in viewing contains an int, you need to use one of the
getInt() methods of ResultSet −
S.N. Methods & Description
1 public int getInt(String columnName) throws SQLException
Returns the int in the current row in the column named columnName.
2 public int getInt(int columnIndex) throws SQLException
Returns the int in the current row in the specified column index. The column index
starts at 1, meaning the first column of a row is 1, the second column of a row is 2,
and so on.
Similarly, there are get methods in the ResultSet interface for each of the eight Java primitive types,
as well as common types such as java.lang.String, java.lang.Object, and java.net.URL.
There are also methods for getting SQL data types java.sql.Date, java.sql.Time,
java.sql.TimeStamp, java.sql.Clob, and java.sql.Blob. Check the documentation for more
information about using these SQL data types.
104
For a better understanding, let us study Viewing - Example Code.
Updatinga Result Set
The ResultSet interface contains a collection of update methods for updating the data of a result
set.
As with the get methods, there are two update methods for each data type −
One that takes in a column name.
105
JAVA PROGRAMS
Display odd numbers between 1 -100
class OddNumber {
public static void main(String args[])
{ System.out.println("The Odd Numbers
are:");for (int i = 1; i <= 100; i++) {
if (i % 2 != 0) {
System.out.print(i + " ");
}
}
}
}
}
Calculate electricity bill
public class ElectricBill
{
public static void main(String args[])
{
int units = 123;
int bill = 0;
}
if (arg == sum)
{
System.out.println("Given number is armstrong number: " + arg);
}
else
{
System.out.println("Given number is not armstrong number: " + arg);
}
}
}
Program to print Armstrong number between 1 to 1000
public class ArmstrongNumbers
{
if (sum == i)
{
System.out.print(i + " ");
}
sum = 0;
}
}
Print given number in words
public class NumberToWords
{
String ten[] = { " ", " ", " Twenty", " Thirty", " Forty", " Fifty", " Sixty", "Seventy", " Eighty",
" Ninety" };
if (n > 19)
{
System.out.print(ten[n / 10] + " " + one[n % 10]);
}
else
{
System.out.print(one[n]);
}
if (n > 0)
System.out.print(ch);
}
int n=28;
System.out.print(n);
if (n <= 0)
{
System.out.println("Enter numbers greater than 0");
}
else
{
NumberToWords a = new NumberToWords();
a.pw((n / 1000000000), " Hundred");
a.pw((n / 10000000) % 100, " crore");
a.pw(((n / 100000) % 100), " lakh");
a.pw(((n / 1000) % 100), " thousand");
a.pw(((n / 100) % 10), " hundred");
a.pw((n % 100), " ");
}
}
}
Program to check the given number is Palindrome or not
public class PalindromeNumberCheck
{
while (n > 0)
{
r = n % 10;
rev = rev * 10 + r;
n = n / 10;
if (rev == pal)
{
System.out.println(" The given no is palindrome "+ rev);
}
else
{
System.out.println("The given no is not palindrome " + rev);
}
}
Program to print palindrome number upto N numbers
public class PalindromeUptoN
{
}
Program to print N prime numbers and find sum and average
public class PrimeNumberUptoN
{
*
**
***
****
*****
***************
******* *******
****** ******
***** *****
**** ****
*** ***
** **
* *
* *
** **
*** ***
**** ****
***** *****
****** ******
******* *******
***************
class FloydsTriangle
{
public static void main(String args[])
{
count++;
}
System.out.println();
}
}
}
1
23
456
7 8 9 10
11 12 13 14 15
16 17 18 19 20 21
Print numbers in sequence way
public class PatternNumberSequence
{
public static void main(String[] args)
{
int a = 3;
int b = 4;
int n = 8;
}
}
}
347
7 5 12
12 6 18
18 7 25
25 8 33
33 9 42
42 10 52
52 11 63
Print numbers in triangle and pyramid vice
1
121
12321
1234321
123454321
import java.util.Scanner;
public class PatternNuberPyramidPrevRev
{
public static void main(String args[])
{
int s = 1;
int n;
Scanner sc = new Scanner(System.in);
System.out.println("Enter the N values");
n = sc.nextInt();
for (int i = 1; i <= n; i++)
{
while (s <= i)
{
System.out.print(s);
s++;
}
s--;
while (s > 1)
{
System.out.print(--s);
}
System.out.println();
}
}
}
1
23
456
7 8 9 10
11 12 13 14 15
}
}
1
12
123
1234
12345
import java.util.Scanner;
int i, j, n;
}
}
}
}
a--;
}
System.out.println();
}
}
}
1
212
32123
4321234
543212345
Print different patterns using stars
*****
****
***
**
*
import java.util.Scanner;
public class Star1
{
public static void main(String args[])
{
int i, j, t;
System.out.println("How many row you want ");
Scanner sc = new Scanner(System.in);
t = sc.nextInt();
for (j = 0; j < t; j++)
{
for (i = t - 1; i >= j; i--)
{
System.out.print("*");
}
System.out.println("");
}
}
}
* *
** **
******
public class Star3
{
public static void main(String[] x)
{
int i, j, k, n = 3;
for (i = 0; i < n; i++)
{
for (j = 0; j <= i; j++)
{
System.out.print("*");
}
for (j = (n - i); j >= 2; j--)
{
System.out.print(" ");
}
for (k = i; k >= 0; k--)
{
System.out.print("*");
}
System.out.println();
}
}
}
*
***
*****
*******
*********
*******
*****
***
*
Print pyramid triangle with star and numbers
public class Star10
{
int arr[] = { 14, 46, 47, 86, 92, 52, 48, 36, 66, 85 };
int largest = arr[0];
int secondLargest = arr[0];
}
}
}
}
Find largest and smallest number in an array in java
public class LargestSmallest
{
public static void main(String[] args)
{
int a[] = new int[] { 23, 34, 13, 64, 72, 90, 10, 15, 9, 27 };
for (int i = 1; i < a.length; i++) // iterate for loop from arrays 1st index (second
element)
{
if (a[i] > max)
{
max = a[i];
}
if (a[i] < min)
{
min = a[i];
}
}
}
Program to find largest and second largest in an array
public class LargestAndSecondLargest
{
public static void main(String[] args)
{
int a[] = new int[] { 12, 44, 23, 56, 23, 78, 13 };
}
Program to remove duplicate element in an array
public class RemoveDuplicateElements
{
public static int[] removeDuplicates(int[] input)
{
int j = 0;
int i = 1;
// return if the array length is less than 2
if (input.length < 2)
{
return input;
}
while (i < input.length)
{
if (input[i] == input[j])
{
i++;
}
else
{
input[++j] = input[i++];
}
}
int[] output = new int[j + 1];
for (int k = 0; k < output.length; k++)
{
output[k] = input[k];
}
return output;
}
{
if (a[i] > a[j])
{
s = a[i];
a[i] = a[j];
a[j] = s;
}
}
if (a[i] % 2 != 0)
{
{
if (a[i] % 2 == 0)
{
}
Program to add two matrix
class MatrixAddition
{
public static void main(String args[])
{
int[][] a = new int[][] { { 1, 2, 3},{ 4, 5, 6},{ 7, 8, 9} };
int[][] b = new int[][] { { 10, 11, 12},{ 13, 14, 15},{ 16, 17, 18} };
int[][] c = new int[3][3];
if(setValue == true)
{
System.out.println("The Given Matrix is a Null Matrix");
}
else
{
System.out.println("The Given Matrix is not a Null Matrix");
}
}
}
Program to check given matrix is diagonal matrix
class DiagonalMatrix
{
public static void main(String args[])
{
int[][] a = new int[][] { { 1, 0, 1},{ 0, 3, 0},{ 0, 0, 3} };
boolean setValue = true;
abc: for(int i = 0;i < a.length;i++)
{
for(int j = 0;j < a[i].length;j++)
{
if(i == j)
{
if(a[i][j] == 0)
{
setValue = false;
break abc;
}
}
else if(a[i][j] != 0)
{
setValue = false;
break abc;
}
}
}
if(setValue == true)
{
System.out.println("The Given Matrix is a Diagonal Matrix");
}
else
{
System.out.println("The Given Matrix is not a Diagonal Matrix");
}
}
}
Program for Linear search
import java.util.Scanner;
class LinearSearch
{
public static void main(String args[])
{
int i, num, searchval, array[];
in.close();
for (i = 0; i < num; i++)
{
if (array[i] == searchval)
{
System.out.println(searchval + " is present at location " + (i + 1));
break;
}
}
if (i == num)
System.out.println(searchval + " is not exist in array.");
}
}
Program for Binary Search
import java.util.Scanner;
public class BinarySearch
{
public static void main(String args[])
{
int counter, num, item, array[], first, last, middle;
Scanner input = new Scanner(System.in);
System.out.println("Enter number of elements:");
num = input.nextInt();
hcf = a;
lcm = (x * y) / hcf;
System.out.println("Number = "+no);
System.out.println("Reverse = "+rev);
}
}
int count = 1;
}
}
System.out.println("Number of words in a string = " + count);
}
}
for(int i=0;i<words.length;i++)
{
for(int j=i+1;j<words.length;j++)
{
if(words[i].equals(words[j]))
{
wrc=wrc+1;
words[j]="0";
}
}
if(words[i]!="0")
System.out.println(words[i]+"--"+wrc);
wrc=1;
}
Program to remove duplicate words in given string
public class RemoveDuplicate
{
for(int j=i+1;j<words.length;j++)
{
if(words[i].equals(words[j]))
{
words[j]=null;
}
}
}
}
for(int k=0;k<words.length;k++)
{
if(words[k]!=null)
{
System.out.println(words[k]);
}
}
}
}
Program to count each words and total number of words in given string
import java.io.IOException;
fr[i]++;
}
}
}
int total = 0;
System.out.println("Words and words count:");
for (int i = 0; i < words.length; i++)
{
if (words[i] != "")
{
System.out.println(words[i] + "=" + fr[i]);
total += fr[i];
}
}
System.out.println("Total words counted: " + total);
}
}
Program to reverse the string and check whether it is palindrome or not
public class PalindromeChecking
{
public static void main(String[] args)
{
String inpstr ="AMMA";
char[] inpArray = inpstr.toCharArray(); char[]
revArray = new char[inpArray.length];int j=0;
for (int i = inpArray.length - 1; i >= 0; i--)
{
revArray[j]=inpArray[i];
j++;
}
String revstr=String.valueOf(revArray);
if(inpstr.equals(revstr))
{
System.out.println("The given string is a Palindrome");
}
else
{
System.out.println("The given string is not a Palindrome");
}
}
}
Program to delete vowels in a given string
public class RemoveAllVovels {
result.append(Character.toUpperCase(words[i].charAt(0))).append(words[i].substring(1)).append
(" ");
System.out.println(result);
}
Program to split a comma-separated string
public class CommaSeparated
{
public static void main(String[] args)
{
String input="Welcome,to,Java Session Session Session";
String[] words=input.split(",");
for(int k=0;k<words.length;k++)
System.out.println(words[k]);
}
}
}
Program to replace vowels with star
public class VowelswithStar
{
public static void main(String[] args)
{
String string = "Welcome to Candid Java Programming"; //Input String
System.out.println("Input String : "+string); //Displaying Input String
string = string.replaceAll("[AaEeIiOoUu]", "*"); //Replace vowels with star
System.out.println(string); //Display the word after replacement
}
Program to print character position count in a given string
public class LetterPositionCount
{
String s = "CANDIDJAVA";
char[] a = s.toCharArray();
int i = 1;
{
for (char output : a)
{
}
}
}
}
Program to print reversed string by word in given line
public class ReverseWord
{
for(int i=1;i<inputArray.length;i++)
{
if(inputArray[i]>maxValue)
{
maxValue=inputArray[i];
}
}
return maxValue;
}
int getMin(int[]inputArray)
{
int minValue=inputArray[0];
for(int i=1;i<inputArray.length;i++)
{
if(inputArray[i]<minValue)
{
minValue=inputArray[i];
}
}
return minValue;
}
}
class NoOfOccurenceOfCharacters
{
static final int MAX_CHAR = 256;
static void getOccuringChar(String str)
{
int count[] = new int[MAX_CHAR];
int len = str.length();
for (int i = 0; i < len; i++)
count[str.charAt(i)]++;
char ch[] = new char[str.length()];
for (int i = 0; i < len; i++) {
ch[i] = str.charAt(i);
int find = 0;
for (int j = 0; j <= i; j++)
{ if (str.charAt(i) ==
ch[j])
find++;
}
if (find == 1)
System.out.println("Number of Occurrence of " +
str.charAt(i) + " is:" + count[str.charAt(i)]);
}
}
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
String str = "geeksforgeeks";
getOccuringChar(str);
}
}
DANDU SRINIVAS
M.Tech
Assistant Professor ,
CSE Department,
Narsimha Reddy Engineering College, Hyderabad.
Prof. Dandu Srinivas working as an Associate Professor in the Computer Science
and Engineering Department at Narsimha Reddy Engineering College, Hyderabad.
He Graduated in Electronics and Computer Engineering from Sreenidhi Institute of
Science and Technology, and a Master's From JNTU, Hyderabad, India. He is in the
Teaching Profession for more than 10 years. He has presented more than 20
papers in National and International Journals and Conferences. He is a lifetime
member of Professional Bodies like ISTE, IAENG, CSI etc.. His main areas of interest
include Artificial Intelligence, Machine Learning, Data Structures, and Algorithms.