Professional Documents
Culture Documents
php)
Home (index.php) Core Java (java/introduction-to-java.php) Collection (java/introduction-to-collection.php) JDBC (java/introduction-to-collection.php)
) (/java/introduction-to-collection.php) )
) (/cpp-programs/cpp-programs.php) )
Our Tutorials Java Tutorials (java/introduction-to-java.php) Collection Tutorials (java/introduction-to-collection.php) JDBC
Tutorials (java/introduction-to-collection.php) C++ Tutorials (cpp/introduction-to-cpp.php)
C++ Programs (cpp-programs/cpp-programs.php) Java Programs (/java-programs/java-programs-example.php)
Tutorialscity 2016
(https://www.facebook.com/tutorialscityindia/) ()
(https://plus.google.com/u/0/108642049011677927484)
TutorialsCity (index.php)
Home (index.php) Core Java (java/introduction-to-java.php) Collection (java/introduction-to-collection.php) JDBC (java/introduction-to-collection.php)
) ) )
) ) )
(https://www.facebook.com/tutorialscityindia/) ()
(https://plus.google.com/u/0/108642049011677927484)
TutorialsCity (../index.php)
Home (../index.php) Core Java (introduction-to-java.php) Collection (introduction-to-collection.php) JDBC (jdbc-in-java.php)
Inheritence (inheritence-in-java.php)
Polymorphism (polymorphism-in-java.php)
Constructor (constructor-in-java.php)
Interface (interface-in-java.php)
String (what-is-string-in-java.php)
MultiThreading (multithreading-in-java.php)
Thread (join-method-in-thread.php)
Swing (swing-in-java.php)
JButton (jbutton-in-java-swing.php)
JRadioButton (jradiobutton-in-java-swing.php)
JTextArea (jtextarea-in-java-swing.php)
JComboBox (jcombobox-in-java-swing.php)
(arraylist-in-collection.php)
LinkList (linklist-in-collection.php)
Vector (vector-in-collection.php)
HashSet (hash-set-in-collection.php)
LinkedHashSet (linkedhashset-in-collection.php)
hashtable (hashtable-in-collection.php)
HashMap (hashmap-in-collection.php)
TreeMap (treemap-in-collection.php)
LinkedHashMap (linkedhashmap-in-collection.php)
arraylist vs linklist (difference-between-arraylist-linklist.php)
JDBC (jdbc-in-java.php)
Introduction To Java
2. Object-Oriented
3. Platform Independent
4. Portable
5. Multi Threaded
Object-Oriented
Platform Independent
Portable
Multi Threaded
Thread is a line of execution. By default only one thread will execute. But Java
allows multiple threads to be run at the same time. So, you can execute many
methods simultaneously .
For Example, In android phone you can run different apps simultaneously.
Speed
Java use Interpreter to run the program because of interpreter it was bit slow to
overcome this problem java introduce JIT Compiler .
Java Interpreter works with JIT Compiler to Run the java Program that makes it fast.
Next (jvm-jre-jdk-in-java.php)
Our Tutorials Java Tutorials (introduction-to-java.php) Collection Tutorials (introduction-to-collection.php) JDBC Tutorials (jdbc-in-
java.php) C++ Tutorials (../cpp/introduction-to-cpp.php)
C++ Programs (../cpp-programs/cpp-programs.php) Java Programs (../java-programs/java-programs-example)
Tutorialscity 2016
(https://www.facebook.com/tutorialscityindia/) ()
(https://plus.google.com/u/0/108642049011677927484)
TutorialsCity (../index.php)
Home (../index.php) Core Java (introduction-to-java.php) Collection (introduction-to-collection.php) JDBC (jdbc-in-java.php)
)
) )
TreeMap (treemap-in-collection.php)
LinkedHashMap (linkedhashmap-in-collection.php)
JDBC (jdbc-in-java.php)
Collection In Java
What Is Collection
In java collection is a container that is used to insert, manipulate, process and traverse
data. Collection contains lot of classes that contain useful methods that makes
developer work easier.
Collection In Java
List
Set
A Set is a Collection that contains only unique elements. There are three types of Set interface: HashSet, LinkedHashSet and TreeSet .
HashSet, LinkedHashSet and TreeSet are implemented by set interface.
Our Tutorials Java Tutorials (introduction-to-java.php) Collection Tutorials (introduction-to-collection.php) JDBC Tutorials (jdbc-in-
java.php) C++ Tutorials (../cpp/introduction-to-cpp.php)
C++ Programs (../cpp-programs/cpp-programs.php) Java Programs (../java-programs/java-programs-example)
Tutorialscity 2016
(https://www.facebook.com/tutorialscityindia/) () (https://plus.google.com/u/0/108642049011677927484)
TutorialsCity (../index.php)
Home (../index.php) Core Java (../java/introduction-to-java.php) Collection (../java/introduction-to-collection.php) JDBC (../java/jdbc-in-java.php)
This Website is under construction Soon C++ tutorials will launch ....:)
Tutorialscity 2016
(https://www.facebook.com/tutorialscityindia/) () (https://plus.google.com/u/0/108642049011677927484)
TutorialsCity (../index.php)
Home (../index.php) Core Java (../java/introduction-to-java.php) Collection (../java/introduction-to-collection.php) JDBC (../java/jdbc-in-java.php)
Tutorialscity 2016
(https://www.facebook.com/tutorialscityindia/) () (https://plus.google.com/u/0/108642049011677927484)
TutorialsCity (../index.php)
Home (../index.php) Core Java (../java/introduction-to-java.php) Collection (../java/introduction-to-collection.php) JDBC (../java/jdbc-in-java.php)
Advantages-Of-OOPS (advantages-of-oops-in-java.php)
String (what-is-string-in-java.php)
Swing (swing-in-java.php)
Collection (introduction-to-collection.php)
JDBC (jdbc-in-java.php)
JDBC In Java
what is JDBC
JDBC is an API that that provide a standard interface for connecting java to different
DBMS. In short JDBC is a technology that used to connect & perform different
operations through java to database.
What is API ?
Tutorialscity 2016
(https://www.facebook.com/tutorialscityindia/) () (https://plus.google.com/u/0/108642049011677927484)
TutorialsCity (../index.php)
Home (../index.php) Core Java (../java/introduction-to-java.php) Collection (../java/introduction-to-collection.php) JDBC (../java/jdbc-in-java.php)
Inheritence (inheritence-in-java.php)
Polymorphism (polymorphism-in-java.php)
Constructor (constructor-in-java.php)
Interface (interface-in-java.php)
String (what-is-string-in-java.php)
MultiThreading (multithreading-in-java.php)
Thread (join-method-in-thread.php)
Swing (swing-in-java.php)
JButton (jbutton-in-java-swing.php)
JRadioButton (jradiobutton-in-java-swing.php)
JTextArea (jtextarea-in-java-swing.php)
JComboBox (jcombobox-in-java-swing.php)
(arraylist-in-collection.php)
LinkList (linklist-in-collection.php)
Vector (vector-in-collection.php)
HashSet (hash-set-in-collection.php)
LinkedHashSet (linkedhashset-in-collection.php)
hashtable (hashtable-in-collection.php)
HashMap (hashmap-in-collection.php)
TreeMap (treemap-in-collection.php)
LinkedHashMap (linkedhashmap-in-collection.php)
arraylist vs linklist (difference-between-arraylist-linklist.php)
JDBC (jdbc-in-java.php)
JVM (Java Virtual Machine) file it can not understand java source
code(.java file). Because .class file contain
The JVM is Java Virtual machine that execute the
byte code.
Java bytecode. The JVM can understand only .class
Java Virtual Machine Java Runtime
Environment Java Development Kit
The JVM can not understand source code(.java file), So
first you need to convert source code to byte code
.you compile your
*.java files to obtain *.class files that contain the
bytecode understandable by the JVM.
In short JVM Interpret the java code and convert it
into machine code for executing code
JRE stands for Java Runtime Environment it contains JVM + other class libraries +
other files that are required to run.
JVM does not exist physically So , in real world JRE execute the Byte code using
the class libraries provided in JRE.
Java Developer Kit is a complete kit that is required to develop the Java programs.
JDK can understand the source code because it contain javac (java compiler) that
compile the code and convert it into byte code .
Byte code produced by JDK is executed by JVM.
if you just want to develop and compile the program then JDK is sucient but in
order to run program JRE is required.
JDK by default contain JRE.
Important Points
Our Tutorials Java Tutorials (introduction-to-java.php) Collection Tutorials (introduction-to-collection.php) JDBC Tutorials (jdbc-in-
java.php) C++ Tutorials (../cpp/introduction-to-cpp.php)
C++ Programs (../cpp-programs/cpp-programs.php) Java Programs (../java-programs/java-programs-example)
Tutorialscity 2016
(https://www.facebook.com/tutorialscityindia/) () (https://plus.google.com/u/0/108642049011677927484)
TutorialsCity (../index.php)
Home (../index.php) Core Java (introduction-to-java.php) Collection (introduction-to-collection.php) JDBC (jdbc-in-java.php)
Inheritence (inheritence-in-java.php)
Polymorphism (polymorphism-in-java.php)
Constructor (constructor-in-java.php)
Interface (interface-in-java.php)
String (what-is-string-in-java.php)
MultiThreading (multithreading-in-java.php)
Thread (join-method-in-thread.php)
Swing (swing-in-java.php)
JButton (jbutton-in-java-swing.php)
JRadioButton (jradiobutton-in-java-swing.php)
JTextArea (jtextarea-in-java-swing.php)
JComboBox (jcombobox-in-java-swing.php)
(arraylist-in-collection.php)
LinkList (linklist-in-collection.php)
Vector (vector-in-collection.php)
HashSet (hash-set-in-collection.php)
LinkedHashSet (linkedhashset-in-collection.php)
hashtable (hashtable-in-collection.php)
HashMap (hashmap-in-collection.php)
TreeMap (treemap-in-collection.php)
LinkedHashMap (linkedhashmap-in-collection.php)
arraylist vs linklist (difference-between-arraylist-linklist.php)
JDBC (jdbc-in-java.php)
Java C++
Java is a pure object oriented language because C++ is partial object oriented language because we can
we cannot create method outside the class. So create method inside the class as well as outside the class.
without class we can create any program in Java. So we can create program with or without class in C++.
In Java, finalize method is used for garbage In C++, destructor function is used for for garbage
collection collection.
Java does not supports multiple inheritance using C++ supports multiple inheritance using classes.
classes.
Java support method overloading but it does not C++ support method overloading as well as operator
support operator overloading. overloading.
Java has package that contain predefined class C++ has header files that contain predefined methods.
and methods.
Java has built-in thread class used to create a C++ has no built-in method or class for threads.C++
new thread in java. depends on third part library for threads
Java support database connectivity with different C++ does not support database connectivity
databases for example: MySQL ,Oracle.
Java source code converted to byte code after C++ source code converted to object code after
compilation. compilation.
Java byte code is platform independent. C++ Object code is platform dependent so code may not
run on different platforms.
Java does not support Templates. C++ support Templates using Templates classes.
Our Tutorials Java Tutorials (introduction-to-java.php) Collection Tutorials (introduction-to-collection.php) JDBC Tutorials (jdbc-in-
java.php) C++ Tutorials (../cpp/introduction-to-cpp.php)
C++ Programs (../cpp-programs/cpp-programs.php) Java Programs (../java-programs/java-programs-example)
Tutorialscity 2016
(https://www.facebook.com/tutorialscityindia/) () (https://plus.google.com/u/0/108642049011677927484)
TutorialsCity (../index.php)
Home (../index.php) Core Java (introduction-to-java.php) Collection (introduction-to-collection.php) JDBC (jdbc-in-java.php)
Inheritence (inheritence-in-java.php)
Polymorphism (polymorphism-in-java.php)
Constructor (constructor-in-java.php)
Interface (interface-in-java.php)
String (what-is-string-in-java.php)
MultiThreading (multithreading-in-java.php)
Thread (join-method-in-thread.php)
Swing (swing-in-java.php)
JButton (jbutton-in-java-swing.php)
JRadioButton (jradiobutton-in-java-swing.php)
JTextArea (jtextarea-in-java-swing.php)
JComboBox (jcombobox-in-java-swing.php)
(arraylist-in-collection.php)
LinkList (linklist-in-collection.php)
Vector (vector-in-collection.php)
HashSet (hash-set-in-collection.php)
LinkedHashSet (linkedhashset-in-collection.php)
hashtable (hashtable-in-collection.php)
HashMap (hashmap-in-collection.php)
TreeMap (treemap-in-collection.php)
LinkedHashMap (linkedhashmap-in-collection.php)
arraylist vs linklist (difference-between-arraylist-linklist.php)
JDBC (jdbc-in-java.php)
In Java java-compiler(javac) is used to compile the java code and JVM is used to
execute the java byte code. we do compilation process and execution process through
cmd. But how cmd knows where is javac and where is JVM . For this we need to set
the Java path. In short Java path specify the path to system where all the required
libraries are present to compile and execute Java code.
There are 2 ways to set java path:
2. Go to C:\Program Files\ find the Java folder if it is not there go to C:\Program Files
Note: if you close the cmd path configuration will lost and if you open a new cmd window
you need to again set the java path.
Step1 : Go to My Computer
properties Step2 : Go to
advanced tab
Step3 : Go to environment
variables Step4 : write path in
variable name
Step5 : paste the jdk\bin path in the varriable value.
Set Java Path in Linux OS
To set Java path in Linux Operating system you need to use export tool rather than set. following steps need to follow to set path in Linux OS:
export PATH=$PATH:/home/jdk1.8.0_25/bin/
Our Tutorials Java Tutorials (introduction-to-java.php) Collection Tutorials (introduction-to-collection.php) JDBC Tutorials (jdbc-in-
java.php) C++ Tutorials (../cpp/introduction-to-cpp.php)
C++ Programs (../cpp-programs/cpp-programs.php) Java Programs (../java-programs/java-programs-example)
Tutorialscity 2016
(https://www.facebook.com/tutorialscityindia/) () (https://plus.google.com/u/0/108642049011677927484)
TutorialsCity (../index.php)
Home (../index.php) Core Java (introduction-to-java.php) Collection (introduction-to-collection.php) JDBC (jdbc-in-java.php)
Inheritence (inheritence-in-java.php)
Polymorphism (polymorphism-in-java.php)
Constructor (constructor-in-java.php)
Interface (interface-in-java.php)
String (what-is-string-in-java.php)
MultiThreading (multithreading-in-java.php)
Thread (join-method-in-thread.php)
Swing (swing-in-java.php)
JButton (jbutton-in-java-swing.php)
JRadioButton (jradiobutton-in-java-swing.php)
JTextArea (jtextarea-in-java-swing.php)
JComboBox (jcombobox-in-java-swing.php)
(arraylist-in-collection.php)
LinkList (linklist-in-collection.php)
Vector (vector-in-collection.php)
HashSet (hash-set-in-collection.php)
LinkedHashSet (linkedhashset-in-collection.php)
hashtable (hashtable-in-collection.php)
HashMap (hashmap-in-collection.php)
TreeMap (treemap-in-collection.php)
LinkedHashMap (linkedhashmap-in-collection.php)
arraylist vs linklist (difference-between-arraylist-linklist.php)
JDBC (jdbc-in-java.php)
Operators In Java
What Is Operator ?
An operator is a symbol used to perform a specific mathematical or logical
operations on operands ( variable ) in a program.
All c operators are valid in c++, it also add some new operators.
what is Operator
List of operators in Java
Arithmetic Operator
Relational Operator Logical Operator Assignment Operator Bitwise Operator
Increment and Decrement Operator
Conditional Operator
Arithmetic Operator
+ 4+2=6
- 42=2
* 4*2=8
/ 4/2=2
% (remainder) 4 % 2= 0
Relational Operator
>
Relational operator Greater than
Meaning
< Less than
== Equals to
!= Not Equal to
Example
Logical Operator
|| Logical OR
! Logical NOT
Assignment Operator:
These are the assignment operators supported by c++. Let value of A=4.
+= A+=2 or A=A+2 6
-= A-=2 or A=A-2 2
*= A*=2 or A=A*2 8
/= A/=2 or A=A/2 2
%= A%=2 or A=A%2 0
*= A*=2 or A=A*2 8
*= A*=2 or A=A*2 8
Bitwise Operator
The bitwise operators are used to perform the operations on data only at bit level.
The following are the bitwise operators:
| OR operator
^ Exclusive OR (XOR)
Output of Truth table for bitwise operator are:
0 0 0 0 0
0 1 0 1 1
1 1 1 1 0
1 0 0 1 1
Example
Example
Z=11;
X=Z++;
Example
Z = 11;
X=--z;
Example
Z=1
1;
X=Z
--;
Conditional Operator
Conditional Operator also known as Ternary Operator is operate on three operands or variables.
Expression1 ? expression2 :
expression3; X=( A>B ) ? A:
B;
Is equal to this statement
If(A>B)
X=A;
Else
X=B;
Prev (set-path-in-java.php) Next (hello-word-program-in-java.php)
Our Tutorials Java Tutorials (introduction-to-java.php) Collection Tutorials (introduction-to-collection.php) JDBC Tutorials (jdbc-in-
java.php) C++ Tutorials (../cpp/introduction-to-cpp.php)
C++ Programs (../cpp-programs/cpp-programs.php) Java Programs (../java-programs/java-programs-example)
Tutorialscity 2016
(https://www.facebook.com/tutorialscityindia/) () (https://plus.google.com/u/0/108642049011677927484)
TutorialsCity (../index.php)
Home (../index.php) Core Java (introduction-to-java.php) Collection (introduction-to-collection.php) JDBC (jdbc-in-java.php)
Inheritence (inheritence-in-java.php)
Polymorphism (polymorphism-in-java.php)
Constructor (constructor-in-java.php)
Interface (interface-in-java.php)
String (what-is-string-in-java.php)
MultiThreading (multithreading-in-java.php)
Thread (join-method-in-thread.php)
Swing (swing-in-java.php)
JButton (jbutton-in-java-swing.php)
JRadioButton (jradiobutton-in-java-swing.php)
JTextArea (jtextarea-in-java-swing.php)
JComboBox (jcombobox-in-java-swing.php)
(arraylist-in-collection.php)
LinkList (linklist-in-collection.php)
Vector (vector-in-collection.php)
HashSet (hash-set-in-collection.php)
LinkedHashSet (linkedhashset-in-collection.php)
hashtable (hashtable-in-collection.php)
HashMap (hashmap-in-collection.php)
TreeMap (treemap-in-collection.php)
LinkedHashMap (linkedhashmap-in-collection.php)
arraylist vs linklist (difference-between-arraylist-linklist.php)
JDBC (jdbc-in-java.php)
(http://www.oracle.com/technetwork/java/javase/downloads/index-jsp-138363.html)
(http://www.tutorialscity.com/java/set-path-in-java.php)
4. Create hello word program in notepad and save it with .java extension i.e. HelloWord.java
Output
Like in C/C++ Programs, we import the header files as a first line of program. Same in
Java we need to import these header files known as class files in Java.
java.lang;
java.lang.String; java.lang.*;
For a Simple hello word program we do not required to import any package.
Java is a pure object oriented programming language. So ,we cannot write a method
outside the class. we create a class with HelloWordExample name.
Inside the class we have a main() methods and syntax of main method is given below:
4. Public
Main method should be public so that it is accessible by JVM. If main method is not
public it is not accessible by JVM and main method define the start point of program
execution so JVM is not able execute the program.
5. Static
Static method can be executed without creating class object. The main method
doesn't require to create a object to invoke the main method. So we declare it as a
static. JVM calls the main method using class name. e.g HelloWordExample.main().
6. Void
Void specify the return type. main() method does not return any value so void should
be used before main() method.
7. String[] args
Args is an array of string type used for command line argument. e.g. we can pass
argument to function when it is called. For example sqrt(10) because main method is
called by JVM so we can pass argument to it through command line .
(https://www.facebook.com/tutorialscityindia/) ()
(https://plus.google.com/u/0/108642049011677927484)
TutorialsCity (../index.php)
Home (../index.php) Core Java (introduction-to-java.php) Collection (introduction-to-collection.php) JDBC (jdbc-in-java.php)
Inheritence (inheritence-in-java.php)
Polymorphism (polymorphism-in-java.php)
Constructor (constructor-in-java.php)
Interface (interface-in-java.php)
String (what-is-string-in-java.php)
MultiThreading (multithreading-in-java.php)
Thread (join-method-in-thread.php)
Swing (swing-in-java.php)
JButton (jbutton-in-java-swing.php)
JRadioButton (jradiobutton-in-java-swing.php)
JTextArea (jtextarea-in-java-swing.php)
JComboBox (jcombobox-in-java-swing.php)
(arraylist-in-collection.php)
LinkList (linklist-in-collection.php)
Vector (vector-in-collection.php)
HashSet (hash-set-in-collection.php)
LinkedHashSet (linkedhashset-in-collection.php)
hashtable (hashtable-in-collection.php)
HashMap (hashmap-in-collection.php)
TreeMap (treemap-in-collection.php)
LinkedHashMap (linkedhashmap-in-collection.php)
arraylist vs linklist (difference-between-arraylist-linklist.php)
JDBC (jdbc-in-java.php)
Local Variables
Instance
Variables Static
Variable
Local Variables
Static Variable
Java is strongly type language it means that every variable must have to declare
before its use and it can contain only that data type. e.g int a; double b ; a=10;
b=10.5 ; we can not write a=10.5 because it is a strongly type language.
Boolean data type has two values true and false.It is used to evaluate logical expressions.
Tutorialscity 2016
(https://www.facebook.com/tutorialscityindia/) () (https://plus.google.com/u/0/108642049011677927484)
TutorialsCity (../index.php)
Home (../index.php) Core Java (introduction-to-java.php) Collection (introduction-to-collection.php) JDBC (jdbc-in-java.php)
Inheritence (inheritence-in-java.php)
Polymorphism (polymorphism-in-java.php)
Constructor (constructor-in-java.php)
Interface (interface-in-java.php)
String (what-is-string-in-java.php)
MultiThreading (multithreading-in-java.php)
Thread (join-method-in-thread.php)
Swing (swing-in-java.php)
JButton (jbutton-in-java-swing.php)
JRadioButton (jradiobutton-in-java-swing.php)
JTextArea (jtextarea-in-java-swing.php)
JComboBox (jcombobox-in-java-swing.php)
(arraylist-in-collection.php)
LinkList (linklist-in-collection.php)
Vector (vector-in-collection.php)
HashSet (hash-set-in-collection.php)
LinkedHashSet (linkedhashset-in-collection.php)
hashtable (hashtable-in-collection.php)
HashMap (hashmap-in-collection.php)
TreeMap (treemap-in-collection.php)
LinkedHashMap (linkedhashmap-in-collection.php)
arraylist vs linklist (difference-between-arraylist-linklist.php)
JDBC (jdbc-in-java.php)
Syntax Of If Statement:
If ( condition )
{
Statements1;
}
Statements2;
If Example
public class IfExample {
public static void main(String[] args) {
int marks = 25;
if (marks < 33) { System.out.println("Fail");
}
System.out.println("Done...");
}
}
Output
Fail
Done...
Here, if condition is true, then statement1 is executed, if given condition is false then statement1 will
not executed.
Statement2 will be executed in both conditions.
If-Else statement is test the given condition if it is true execute the statement inside the if block or if
it is false executes the statement inside else block.
Syntax Of If-else
if (condition) { Statement1;
} else { Statement2;
}
When Given condition is true "Statement1" will executed, else statement2 will executed.
If Else Example
public class IfElseExample {
Output
Pass
Done...
if-else-if ladder is used to test more than one condition e.g if (a>1) execute statement 1 else if (a>2)
execute statement 2 .....etc.
it will test the conditions sequentially if it is matched it executes the block associated with matched if
blocks and skip the other conditions.
Java If Else Ladder
if(condition1){
// execute this block code if condition1 is true
}else if(condition2){
If Else Ladder
public class IfElseExample {
System.out.println("Done...");
}
}
Output
Pass with Second Division
Done...
Our Tutorials Java Tutorials (introduction-to-java.php) Collection Tutorials (introduction-to-collection.php) JDBC Tutorials (jdbc-in-
java.php) C++ Tutorials (../cpp/introduction-to-cpp.php)
C++ Programs (../cpp-programs/cpp-programs.php) Java Programs (../java-programs/java-programs-example)
Tutorialscity 2016
(https://www.facebook.com/tutorialscityindia/) () (https://plus.google.com/u/0/108642049011677927484)
TutorialsCity (../index.php)
Home (../index.php) Core Java (introduction-to-java.php) Collection (introduction-to-collection.php) JDBC (jdbc-in-java.php)
Inheritence (inheritence-in-java.php)
Polymorphism (polymorphism-in-java.php)
Constructor (constructor-in-java.php)
Interface (interface-in-java.php)
String (what-is-string-in-java.php)
MultiThreading (multithreading-in-java.php)
Thread (join-method-in-thread.php)
Swing (swing-in-java.php)
JButton (jbutton-in-java-swing.php)
JRadioButton (jradiobutton-in-java-swing.php)
JTextArea (jtextarea-in-java-swing.php)
JComboBox (jcombobox-in-java-swing.php)
(arraylist-in-collection.php)
LinkList (linklist-in-collection.php)
Vector (vector-in-collection.php)
HashSet (hash-set-in-collection.php)
LinkedHashSet (linkedhashset-in-collection.php)
hashtable (hashtable-in-collection.php)
HashMap (hashmap-in-collection.php)
TreeMap (treemap-in-collection.php)
LinkedHashMap (linkedhashmap-in-collection.php)
arraylist vs linklist (difference-between-arraylist-linklist.php)
JDBC (jdbc-in-java.php)
Switch In Java
Java Switch
Break keyword in switch statement stop the execution of current loop and exit the
control from switch statement.
public class JavaSwitchExample { public static void main(String[] int value = 300;
switch (value) {
case 100: System.out.println("100"); break; args) {
case 200: System.out.println("200"); break;
case 300: System.out.println("300"); break;
default:
Output
300
if you do not break statement in switch block it will execute all the statement after first match.
case 300:
System.out.println("300");
default:
System.out.println("Not in 100, 200 or 300");
}
}
Output
300
Not in 100, 200 or 300
Our Tutorials Java Tutorials (introduction-to-java.php) Collection Tutorials (introduction-to-collection.php) JDBC Tutorials (jdbc-in-
java.php) C++ Tutorials (../cpp/introduction-to-cpp.php)
C++ Programs (../cpp-programs/cpp-programs.php) Java Programs (../java-programs/java-programs-example)
Tutorialscity 2016
(https://www.facebook.com/tutorialscityindia/) () (https://plus.google.com/u/0/108642049011677927484)
TutorialsCity (../index.php)
Home (../index.php) Core Java (introduction-to-java.php) Collection (introduction-to-collection.php) JDBC (jdbc-in-java.php)
Inheritence (inheritence-in-java.php)
Polymorphism (polymorphism-in-java.php)
Constructor (constructor-in-java.php)
Interface (interface-in-java.php)
String (what-is-string-in-java.php)
MultiThreading (multithreading-in-java.php)
Thread (join-method-in-thread.php)
Swing (swing-in-java.php)
JButton (jbutton-in-java-swing.php)
JRadioButton (jradiobutton-in-java-swing.php)
JTextArea (jtextarea-in-java-swing.php)
JComboBox (jcombobox-in-java-swing.php)
(arraylist-in-collection.php)
LinkList (linklist-in-collection.php)
Vector (vector-in-collection.php)
HashSet (hash-set-in-collection.php)
LinkedHashSet (linkedhashset-in-collection.php)
hashtable (hashtable-in-collection.php)
HashMap (hashmap-in-collection.php)
TreeMap (treemap-in-collection.php)
LinkedHashMap (linkedhashmap-in-collection.php)
arraylist vs linklist (difference-between-arraylist-linklist.php)
JDBC (jdbc-in-java.php)
Loops In Java
For Loop
While Loop
Do-While Loop
statements;
.....
}
In step 2 condition has been tested. if condition hold true, statement is executed
otherwise loop is terminated.
In step 3 variable value incremented or decremented based on expression
for(int i=0;i<10;i++)
{
System.out.println(i);
}
}
}
Output
0
1
2
3
4
5
6
7
8
9
}
}
Output
0 0
0 1
0 2
1 0
1 1
1 2
Our Tutorials Java Tutorials (introduction-to-java.php) Collection Tutorials (introduction-to-collection.php) JDBC Tutorials (jdbc-in-
java.php) C++ Tutorials (../cpp/introduction-to-cpp.php)
C++ Programs (../cpp-programs/cpp-programs.php) Java Programs (../java-programs/java-programs-example)
Tutorialscity 2016
(https://www.facebook.com/tutorialscityindia/) () (https://plus.google.com/u/0/108642049011677927484)
TutorialsCity (../index.php)
Home (../index.php) Core Java (introduction-to-java.php) Collection (introduction-to-collection.php) JDBC (jdbc-in-java.php)
Inheritence (inheritence-in-java.php)
Polymorphism (polymorphism-in-java.php)
Constructor (constructor-in-java.php)
Interface (interface-in-java.php)
String (what-is-string-in-java.php)
MultiThreading (multithreading-in-java.php)
Thread (join-method-in-thread.php)
Swing (swing-in-java.php)
JButton (jbutton-in-java-swing.php)
JRadioButton (jradiobutton-in-java-swing.php)
JTextArea (jtextarea-in-java-swing.php)
JComboBox (jcombobox-in-java-swing.php)
(arraylist-in-collection.php)
LinkList (linklist-in-collection.php)
Vector (vector-in-collection.php)
HashSet (hash-set-in-collection.php)
LinkedHashSet (linkedhashset-in-collection.php)
hashtable (hashtable-in-collection.php)
HashMap (hashmap-in-collection.php)
TreeMap (treemap-in-collection.php)
LinkedHashMap (linkedhashmap-in-collection.php)
arraylist vs linklist (difference-between-arraylist-linklist.php)
JDBC (jdbc-in-java.php)
while ( condition )
{
statements;
}
Here ,condition get tested by compiler , if condition is true then statements are executed otherwise loop
is not executed and control is transfer out of loop.
Output
0
1
2
3
4
5
6
7
8
9
Our Tutorials Java Tutorials (introduction-to-java.php) Collection Tutorials (introduction-to-collection.php) JDBC Tutorials (jdbc-in-
java.php) C++ Tutorials (../cpp/introduction-to-cpp.php)
C++ Programs (../cpp-programs/cpp-programs.php) Java Programs (../java-programs/java-programs-example)
Tutorialscity 2016
(https://www.facebook.com/tutorialscityindia/) () (https://plus.google.com/u/0/108642049011677927484)
TutorialsCity (../index.php)
Home (../index.php) Core Java (introduction-to-java.php) Collection (introduction-to-collection.php) JDBC (jdbc-in-java.php)
Inheritence (inheritence-in-java.php)
Polymorphism (polymorphism-in-java.php)
Constructor (constructor-in-java.php)
Interface (interface-in-java.php)
String (what-is-string-in-java.php)
MultiThreading (multithreading-in-java.php)
Thread (join-method-in-thread.php)
Swing (swing-in-java.php)
JButton (jbutton-in-java-swing.php)
JRadioButton (jradiobutton-in-java-swing.php)
JTextArea (jtextarea-in-java-swing.php)
JComboBox (jcombobox-in-java-swing.php)
(arraylist-in-collection.php)
LinkList (linklist-in-collection.php)
Vector (vector-in-collection.php)
HashSet (hash-set-in-collection.php)
LinkedHashSet (linkedhashset-in-collection.php)
hashtable (hashtable-in-collection.php)
HashMap (hashmap-in-collection.php)
TreeMap (treemap-in-collection.php)
LinkedHashMap (linkedhashmap-in-collection.php)
arraylist vs linklist (difference-between-arraylist-linklist.php)
JDBC (jdbc-in-java.php)
Do-while loop Do-while loop is same as while loop except the condition
is tested after the execution of loop Therefore, it is called
an exit controlled loop.
Do-while loop Syntax Of Do-
While Loop Do While Example In
Java
Syntax Of Do-While Loop
Do
{
Statements;
}
While ( condition );
Here, statements inside Do block will be executed at least one time weather condition is true or false
because condition is going to be tested after rst execution. therefore, loop is executed at least one time
in Do-while loop.
do
{
System.out.println(i);
i++;
}while(i<10);
}
Output
12
(https://www.facebook.com/tutorialscityindia/) () (https://plus.google.com/u/0/108642049011677927484)
TutorialsCity (../index.php)
Home (../index.php) Core Java (introduction-to-java.php) Collection (introduction-to-collection.php) JDBC (jdbc-in-java.php)
Inheritence (inheritence-in-java.php)
Polymorphism (polymorphism-in-java.php)
Constructor (constructor-in-java.php)
Interface (interface-in-java.php)
String (what-is-string-in-java.php)
MultiThreading (multithreading-in-java.php)
Thread (join-method-in-thread.php)
Swing (swing-in-java.php)
JButton (jbutton-in-java-swing.php)
JRadioButton (jradiobutton-in-java-swing.php)
JTextArea (jtextarea-in-java-swing.php)
JComboBox (jcombobox-in-java-swing.php)
(arraylist-in-collection.php)
LinkList (linklist-in-collection.php)
Vector (vector-in-collection.php)
HashSet (hash-set-in-collection.php)
LinkedHashSet (linkedhashset-in-collection.php)
hashtable (hashtable-in-collection.php)
HashMap (hashmap-in-collection.php)
TreeMap (treemap-in-collection.php)
LinkedHashMap (linkedhashmap-in-collection.php)
arraylist vs linklist (difference-between-arraylist-linklist.php)
JDBC (jdbc-in-java.php)
Break In Java
Break
The term break refers to act of breaking the loop if the specified condition meet.
Break Example
public class BreakExample {
public static void main(String[] args) {
for(int i=0;i<=5;i++){
if(i==3){
break;
}
System.out.println(i);
}
System.out.println("Out of loop");
}
}
Output
0
1
2
Out of loop
for(int i=0;i<=2;i++){
for(int j=0;j<=3;j++)
{
if(j>i){ System.out.println("Break..");
break;
}
System.out.println(i+" "+j);
}
}
System.out.println("Out of loop");
}
}
Output
0 0
Break.. 1 0
1 1
Break.. 2 0
2 1
2 2
Break..
Out of loop
Our Tutorials Java Tutorials (introduction-to-java.php) Collection Tutorials (introduction-to-collection.php) JDBC Tutorials (jdbc-in-
java.php) C++ Tutorials (../cpp/introduction-to-cpp.php)
C++ Programs (../cpp-programs/cpp-programs.php) Java Programs (../java-programs/java-programs-example)
Tutorialscity 2016
(https://www.facebook.com/tutorialscityindia/) () (https://plus.google.com/u/0/108642049011677927484)
TutorialsCity (../index.php)
Home (../index.php) Core Java (introduction-to-java.php) Collection (introduction-to-collection.php) JDBC (jdbc-in-java.php)
Inheritence (inheritence-in-java.php)
Polymorphism (polymorphism-in-java.php)
Constructor (constructor-in-java.php)
Interface (interface-in-java.php)
String (what-is-string-in-java.php)
MultiThreading (multithreading-in-java.php)
Thread (join-method-in-thread.php)
Swing (swing-in-java.php)
JButton (jbutton-in-java-swing.php)
JRadioButton (jradiobutton-in-java-swing.php)
JTextArea (jtextarea-in-java-swing.php)
JComboBox (jcombobox-in-java-swing.php)
(arraylist-in-collection.php)
LinkList (linklist-in-collection.php)
Vector (vector-in-collection.php)
HashSet (hash-set-in-collection.php)
LinkedHashSet (linkedhashset-in-collection.php)
hashtable (hashtable-in-collection.php)
HashMap (hashmap-in-collection.php)
TreeMap (treemap-in-collection.php)
LinkedHashMap (linkedhashmap-in-collection.php)
arraylist vs linklist (difference-between-arraylist-linklist.php)
JDBC (jdbc-in-java.php)
Continue is similar to break expect that instead of breaking the loop it will skip current iteration and start
the next iteration .
Continue Example In Java
public class ContinueExample {
public static void main(String[] args) {
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 3; j++) {
if (i == j)
continue;
System.out.println(i + " " + j);
Output
0 1
0 2
1 0
1 2
Tutorialscity 2016
(https://www.facebook.com/tutorialscityindia/) () (https://plus.google.com/u/0/108642049011677927484)
TutorialsCity (../index.php)
Home (../index.php) Core Java (introduction-to-java.php) Collection (introduction-to-collection.php) JDBC (jdbc-in-java.php)
Inheritence (inheritence-in-java.php)
Polymorphism (polymorphism-in-java.php)
Constructor (constructor-in-java.php)
String (what-is-string-in-java.php)
Swing (swing-in-java.php)
Collection (introduction-to-collection.php)
JDBC (jdbc-in-java.php)
Re-usability
Inheritance
Abstraction
Easy To Develop
Easy To Maintain
Reduce Complexity
Inheritance
Inheritance is process by which one thing can acquire some property of another
thing. Like, children can acquire some properties of their parents by birth. Inheritance
concept allow us to define a class by using another class without making change to it.
Abstraction
Abstraction means hiding the information that is not required for client.
For e.g. In your mobile phone when you press a button it will perform a specific operation.
Call button is used for calling but user actually do not know how it works. The actual
process is totally hidden that is known as abstraction.
Easy to Develop
Object oriented language provide the concept of class and object, so code is easy to develop.
Easy to Maintain
If in future any modification required in code or you need to add some more features it
is bit easy because of Oops concepts.
For e.g. Change inside one class method do not effects other part of the program.
Oops provide class and objects which capture the actual code. So, complete code is
viewed as a collection of different classes and objects. It reduce the complexity of a
program and easy to understand.
Our Tutorials Java Tutorials (introduction-to-java.php) Collection Tutorials (introduction-to-collection.php) JDBC Tutorials (jdbc-in-
java.php) C++ Tutorials (../cpp/introduction-to-cpp.php)
C++ Programs (../cpp-programs/cpp-programs.php) Java Programs (../java-programs/java-programs-example)
Tutorialscity 2016
(https://www.facebook.com/tutorialscityindia/) () (https://plus.google.com/u/0/108642049011677927484)
TutorialsCity (../index.php)
Home (../index.php) Core Java (introduction-to-java.php) Collection (introduction-to-collection.php) JDBC (jdbc-in-java.php)
Inheritence (inheritence-in-java.php)
Polymorphism (polymorphism-in-java.php)
Constructor (constructor-in-java.php)
String (what-is-string-in-java.php)
Swing (swing-in-java.php)
Collection (introduction-to-collection.php)
JDBC (jdbc-in-java.php)
A class is a blue print or template that define the methods and variables for the objects .
Object
Now hondacity,audi are the objects of car . So without object, class does not have any existence.
Classes are user dened data types but behave like built-in functions. Their Objects are behaved like
variable of type class.
Output
Done..
Our Tutorials Java Tutorials (introduction-to-java.php) Collection Tutorials (introduction-to-collection.php) JDBC Tutorials (jdbc-in-
java.php) C++ Tutorials (../cpp/introduction-to-cpp.php)
C++ Programs (../cpp-programs/cpp-programs.php) Java Programs (../java-programs/java-programs-example)
Tutorialscity 2016
(https://www.facebook.com/tutorialscityindia/) () (https://plus.google.com/u/0/108642049011677927484)
TutorialsCity (../index.php)
Home (../index.php) Core Java (introduction-to-java.php) Collection (introduction-to-collection.php) JDBC (jdbc-in-java.php)
Inheritence (inheritence-in-java.php)
Polymorphism (polymorphism-in-java.php)
Constructor (constructor-in-java.php)
String (what-is-string-in-java.php)
Swing (swing-in-java.php)
Collection (introduction-to-collection.php)
JDBC (jdbc-in-java.php)
Inheritance is process by which one thing can acquire some property of another
thing. Like, children can acquire some properties of their parents by birth.
Similarly , Inheitance concept in Java allow us to define a class by using another class
without making change to it. This can be done By DERIVED and BASE CLASS. The new
generated class is called derived class and existing one is called base class.
Types Of Inheritance
Single Inheritence
Multilevel Inheritence
Hirerichal Inheritence
Multiple Inheritence
Advantage of Inheritance concept:
Reduce the wastage of time and memory while defining the same new data
member and functions in derived class.
Increase the functionality of an existing class.
Derived class is defined through base class by including some own information of derived class in it.
void display()
{
System.out.println("display child data");
}
public static void main(String[] args) {
}
}
Output
get data from parent display child data
class parentclass1 {
void Test() {
System.out.println("parent1 Test method");
}
}
class parentclass2 {
void Test() {
System.out.println("parent2 Test method ");
}
}
class child extends parentclass1,parentclass2 {
public static void main(String args[]) { child obj = new child();
obj.Test(); // Now which Test() method would be invoked? So amiguity arise
}
}
Our Tutorials Java Tutorials (introduction-to-java.php) Collection Tutorials (introduction-to-collection.php) JDBC Tutorials (jdbc-in-
java.php) C++ Tutorials (../cpp/introduction-to-cpp.php)
C++ Programs (../cpp-programs/cpp-programs.php) Java Programs (../java-programs/java-programs-example)
Tutorialscity 2016
(https://www.facebook.com/tutorialscityindia/) () (https://plus.google.com/u/0/108642049011677927484)
TutorialsCity (../index.php)
Home (../index.php) Core Java (introduction-to-java.php) Collection (introduction-to-collection.php) JDBC (jdbc-in-java.php)
Inheritence (inheritence-in-java.php)
Polymorphism (polymorphism-in-java.php)
Constructor (constructor-in-java.php)
String (what-is-string-in-java.php)
Swing (swing-in-java.php)
Collection (introduction-to-collection.php)
JDBC (jdbc-in-java.php)
Due to this, the data of class is not accessible from outside the class, only
functions of that particular class can access that data.
This makes the program more safer and secure because no one can access data
from outside and misuse it.
This feature is not present in procedure oriented programing, hence in
procedure oriented programing, data can be easily accessible and
corrupted than oop.
Encapsulation in C++ also gives the concept of Data Hiding.
Advantages Of Encapsulation
The data is not corrupted by external world which gives program more security.
It ensures that any change in data and functions of an object can be made
without affecting other objects.
Data cannot be intentionally or unintentionally corrupted by any external world.
Data Abstraction
Abstraction means represent only essential features without showing background detail.
By using this, they provide the users to directly Using the functionality of program
without knowing that how class has been implemented internally.
Example:
1. In your mobile phone when you press a button it will perform a specific operation.
Like call button is used to calling but you actually do not know how it works. The
2. Gamer play game and enjoy the game without knowing its complete coding detail.
3. Users chat with his friend on social network sites like facebook without knowing that
how that message is send and receiver by another user, which streaming is used
to do.
Our Tutorials Java Tutorials (introduction-to-java.php) Collection Tutorials (introduction-to-collection.php) JDBC Tutorials (jdbc-in-
java.php) C++ Tutorials (../cpp/introduction-to-cpp.php)
C++ Programs (../cpp-programs/cpp-programs.php) Java Programs (../java-programs/java-programs-example)
Tutorialscity 2016
(https://www.facebook.com/tutorialscityindia/) () (https://plus.google.com/u/0/108642049011677927484)
TutorialsCity (../index.php)
Home (../index.php) Core Java (introduction-to-java.php) Collection (introduction-to-collection.php) JDBC (jdbc-in-java.php)
Inheritence (inheritence-in-java.php)
Polymorphism (polymorphism-in-java.php)
Constructor (constructor-in-java.php)
String (what-is-string-in-java.php)
Swing (swing-in-java.php)
Collection (introduction-to-collection.php)
JDBC (jdbc-in-java.php)
Polymorphism means one name and many duties or work. It means the ability to take
more than one form.
Hence in polymorphism, an operation can behave differently in different situations.
Example
In an Operation of addition ( + ).
If the operation is held on two integer then operation will generate a sum and if
operation is held on two string then operation is concatenation.
Types of Polymorphism:
STATIC BINDING
DYNAMIC BINDING
Here, Binding simply means to linking of function call to the code to be executed in response to that call.
1. STATIC BINDING
mean that code associated with a given function call is known at compile time, hence it is also known as early
binding or compile time polymorphism.
2. DYNAMIC BINDING
means that the code associated with given function call is not known until the time of call at run time. So Code is
linked with function call only at run time.
Hence it is also known as Late Binding.
import java.lang.*;
class MethodOverridingExample
{ public static void main(String
args[]) { BasicAccount obj1,
obj2, obj3;
obj1 = new BasicAccount();
obj1.createAccount();
obj2 = new SavingAccount();
obj2.createAccount();
obj3 = new CurrentAccount();
obj3.createAccount();
Output
Tutorialscity 2016
(https://www.facebook.com/tutorialscityindia/) () (https://plus.google.com/u/0/108642049011677927484)
TutorialsCity (../index.php)
Home (../index.php) Core Java (introduction-to-java.php) Collection (introduction-to-collection.php) JDBC (jdbc-in-java.php)
Inheritence (inheritence-in-java.php)
Polymorphism (polymorphism-in-java.php)
Constructor (constructor-in-java.php)
String (what-is-string-in-java.php)
Swing (swing-in-java.php)
Collection (introduction-to-collection.php)
JDBC (jdbc-in-java.php)
A constructor is a special method whose name is same as class name and it is used
to initialize variables when an object of a class is created.
In Java Every class have a constructor, if you don't specify a constructor explicitly in
any java class in that case the compiler create a default constructor in that class.
In java Default constructor is a method whose name is same as class name and it does
not contain any parameter.
In java Parameterized constructor is a method whose name is same as class name and it
contain one or more than one parameter.
Output
Prameterized Constructor 1 called value = 10
Prameterized Constructor 2 called value1 = 10 value2 = 20
Our Tutorials Java Tutorials (introduction-to-java.php) Collection Tutorials (introduction-to-collection.php) JDBC Tutorials (jdbc-in-
java.php) C++ Tutorials (../cpp/introduction-to-cpp.php)
C++ Programs (../cpp-programs/cpp-programs.php) Java Programs (../java-programs/java-programs-example)
Tutorialscity 2016
(https://www.facebook.com/tutorialscityindia/) () (https://plus.google.com/u/0/108642049011677927484)
TutorialsCity (../index.php)
Home (../index.php) Core Java (introduction-to-java.php) Collection (introduction-to-collection.php) JDBC (jdbc-in-java.php)
Inheritence (inheritence-in-java.php)
Polymorphism (polymorphism-in-java.php)
Constructor (constructor-in-java.php)
String (what-is-string-in-java.php)
Swing (swing-in-java.php)
Collection (introduction-to-collection.php)
JDBC (jdbc-in-java.php)
class SavingAccount {
SavingAccount() { System.out.println("Saving
}
Account Created Balance = Nil");
}
Output
Saving Account Created Balance = Nil Saving Account Created Balance = 1000
this Program
class ThisExample {
int a = 10;
public void setvalue(int a) { System.out.println("a=" + a); System.out.println("this.a=" + this.a);
}
public static void main(String a[]) { ThisExample obj = new ThisExample(); obj.setvalue(20);
}
}
Example
a=20
this.a=10
Program Explanation
here this.a refer to instance variable(class member variable) and a would refer to argument in the setvalue . So, in order to refer class variable this.a is requ
Our Tutorials Java Tutorials (introduction-to-java.php) Collection Tutorials (introduction-to-collection.php) JDBC Tutorials (jdbc-in-
java.php) C++ Tutorials (../cpp/introduction-to-cpp.php)
C++ Programs (../cpp-programs/cpp-programs.php) Java Programs (../java-programs/java-programs-example)
Tutorialscity 2016
(https://www.facebook.com/tutorialscityindia/) () (https://plus.google.com/u/0/108642049011677927484)
TutorialsCity (../index.php)
Home (../index.php) Core Java (introduction-to-java.php) Collection (introduction-to-collection.php) JDBC (jdbc-in-java.php)
Inheritence (inheritence-in-java.php)
Polymorphism (polymorphism-in-java.php)
Constructor (constructor-in-java.php)
String (what-is-string-in-java.php)
Swing (swing-in-java.php)
Collection (introduction-to-collection.php)
JDBC (jdbc-in-java.php)
static Keyword in java is used to create a shared Variable, Method or nested class for all objects.
i.e. if a class contain a static variable in that case this variable is common for all the objects of the
class.
Static Keyword is related to class not with class object.
variable
Method
Nested class
Block
In java if you declare any variable with static keyword , it is known static variable.
Static variable are related to class not related to objects of the class.
The static variable is shared variable for all objects. It means if a class have 10 objects each object
refer to same static variable.
The static variable gets memory at time of class loading So, it is related to class not related to object.
we can call static variable directly without class object.ie classname.staticVarriableName().
Employee e1 = new Employee(1, "Abhi"); Employee e2 = new Employee(2, "Moni"); Employee e3 = new Employee(3, "rahul"); e1.display();
e2.display();
e3.display();
}
}
Output
Infosys 1 Abhi
Infosys 2 Moni
Infosys 3 rahul
Java static Method
In java if you declare any method with static keyword , it is known static method.
Static method are related to class not related to objects of the class.
The static methods is shared among all objects.
The static method can change the value of static data member.
}
void display() {
System.out.println(companyName + " " + empid + " " + name);
e2.display();
e3.display();
Output
Infosys 1 Abhi
Infosys 2 Moni
Infosys 3 rahul
It's a block of code which is executed when the class gets loaded by a classloader.
Static block is used for initialization of static class members .
Static block of code is executed before the main() function at the time of class loading.
With static block you can execute set of code without the main function.
class StaticBlockExample{ static{System.out.println("static block is called..");} public static void main(String args[]){ System.out.println("main method
}
}
Output
static block is called..
main method is called..
Our Tutorials Java Tutorials (introduction-to-java.php) Collection Tutorials (introduction-to-collection.php) JDBC Tutorials (jdbc-in-
java.php) C++ Tutorials (../cpp/introduction-to-cpp.php)
C++ Programs (../cpp-programs/cpp-programs.php) Java Programs (../java-programs/java-programs-example)
Tutorialscity 2016
(https://www.facebook.com/tutorialscityindia/) () (https://plus.google.com/u/0/108642049011677927484)
TutorialsCity (../index.php)
Home (../index.php) Core Java (introduction-to-java.php) Collection (introduction-to-collection.php) JDBC (jdbc-in-java.php)
Inheritence (inheritence-in-java.php)
Polymorphism (polymorphism-in-java.php)
Constructor (constructor-in-java.php)
String (what-is-string-in-java.php)
Swing (swing-in-java.php)
Collection (introduction-to-collection.php)
JDBC (jdbc-in-java.php)
Super keyword in java used to call super class or parent class members.
Super keyword is used to call constructor of parent class, parent class method and parent class
variable .
if a parent class contain variable with same name as child class in that case in order to call parent
class variable we need to use super keyword.
if a parent class contain method with same name as child class. in that case in order to call parent
method we need to use super keyword.
Super keyword also used to call parent class constructor. e.g. Default constructor can be called as
Super() and parameterized constructor can be called as super(parameters list).
Output
10000
Output
50000
Output
Output
class student {
void msg() {
System.out.println("Student class method");
}
}
class Btech extends student {
void msg() {
System.out.println("Btech class method");
}
void display() { msg();
super.msg(); System.out.println("Done....");
}
public static void main(String args[]) { Btech obj = new Btech();
obj.display();
}
}
Output
Our Tutorials Java Tutorials (introduction-to-java.php) Collection Tutorials (introduction-to-collection.php) JDBC Tutorials (jdbc-in-
java.php) C++ Tutorials (../cpp/introduction-to-cpp.php)
C++ Programs (../cpp-programs/cpp-programs.php) Java Programs (../java-programs/java-programs-example)
Tutorialscity 2016
(https://www.facebook.com/tutorialscityindia/) () (https://plus.google.com/u/0/108642049011677927484)
TutorialsCity (../index.php)
Home (../index.php) Core Java (introduction-to-java.php) Collection (introduction-to-collection.php) JDBC (jdbc-in-java.php)
Inheritence (inheritence-in-java.php)
Polymorphism (polymorphism-in-java.php)
Constructor (constructor-in-java.php)
String (what-is-string-in-java.php)
Swing (swing-in-java.php)
Collection (introduction-to-collection.php)
JDBC (jdbc-in-java.php)
Final Varribale
The value of final variable can not be changed.
final variables must be initialized when created.ie
final int a=10. Once value is you initialized it cannot
be changed.
In java final variables are constants.
Program Explanation
Final Method
Output
Final Class
Output
Our Tutorials Java Tutorials (introduction-to-java.php) Collection Tutorials (introduction-to-collection.php) JDBC Tutorials (jdbc-in-
java.php) C++ Tutorials (../cpp/introduction-to-cpp.php)
C++ Programs (../cpp-programs/cpp-programs.php) Java Programs (../java-programs/java-programs-example)
Tutorialscity 2016
(https://www.facebook.com/tutorialscityindia/) () (https://plus.google.com/u/0/108642049011677927484)
TutorialsCity (../index.php)
Home (../index.php) Core Java (introduction-to-java.php) Collection (introduction-to-collection.php) JDBC (jdbc-in-java.php)
Inheritence (inheritence-in-java.php)
Polymorphism (polymorphism-in-java.php)
Constructor (constructor-in-java.php)
String (what-is-string-in-java.php)
Swing (swing-in-java.php)
Collection (introduction-to-collection.php)
JDBC (jdbc-in-java.php)
Method Overloading is a process in which we can create more than one method with
same name till the time parameters are different .
System.out.println(a * a);
}
void square(oat a) System.out.println(a
} {
* a);
public static void main(String[] args) { MethodOverloadExample obj = new MethodOverloadExample(); obj.square(10);
obj.square(10.2f);
}
}
Output
104.03999
public static void main(String[] args) { MethodOverloadExample obj = new MethodOverloadExample(); obj.square(10);
obj.square(10,20); obj.square(10,20,30);
}
}
Output
100
500
1400
}
Output
100
102.01001
200
202.01001
Output
t1 called
t2 called
Output
main method with integer argument main method with oat argument
Output
Tutorialscity 2016
(https://www.facebook.com/tutorialscityindia/) () (https://plus.google.com/u/0/108642049011677927484)
TutorialsCity (../index.php)
Home (../index.php) Core Java (introduction-to-java.php) Collection (introduction-to-collection.php) JDBC (jdbc-in-java.php)
Inheritence (inheritence-in-java.php)
Polymorphism (polymorphism-in-java.php)
Constructor (constructor-in-java.php)
String (what-is-string-in-java.php)
Swing (swing-in-java.php)
Collection (introduction-to-collection.php)
JDBC (jdbc-in-java.php)
Method Overriding is only way in java to implement parent class method in the child class.
class BasicAccount {
void createAccount() { System.out.println("Basic Account Created");
}
}
class MethodOverridingExample {
public static void main(String BasicAccount obj1, obj2, obj3; obj1 = new BasicAccount();
args[]) { obj1.createAccount();
obj2 = new SavingAccount(); obj2.createAccount();
obj3 = new CurrentAccount();
obj3.createAccount();
}
}
Output
Basic Account Created
Saving Account Created Current Account Created
Our Tutorials Java Tutorials (introduction-to-java.php) Collection Tutorials (introduction-to-collection.php) JDBC Tutorials (jdbc-in-
java.php) C++ Tutorials (../cpp/introduction-to-cpp.php)
C++ Programs (../cpp-programs/cpp-programs.php) Java Programs (../java-programs/java-programs-example)
Tutorialscity 2016
(https://www.facebook.com/tutorialscityindia/) () (https://plus.google.com/u/0/108642049011677927484)
TutorialsCity (../index.php)
Home (../index.php) Core Java (introduction-to-java.php) Collection (introduction-to-collection.php) JDBC (jdbc-in-java.php)
Inheritence (inheritence-in-java.php)
Polymorphism (polymorphism-in-java.php)
Constructor (constructor-in-java.php)
String (what-is-string-in-java.php)
Swing (swing-in-java.php)
Collection (introduction-to-collection.php)
JDBC (jdbc-in-java.php)
Inte
Array In Java
Java Array
Array stores the data on Index basis i.e. At 0 index first value is stored .
System.out.println("Student Marks:");
// Display array values
// sub.length returns the number of
for (int i = 0; i < sub.length; i++) System.out.println(sub[i]);
elements of an array
}
}
Output
Student Marks: 50
60
70
40
80
Multidimensional Array
Multidimensional Array have more than one subscript. i.e. Two Dimensional have 2 subscript ie a[][]
class ArrayExample {
public static void main(String args[]) {
int matrix1[][] = new int[2][2]; // declaration of array 1 int matrix2[][] = new int[2][2]; // declaration of array 2
matrix1[0][1] = 20;
matrix1[1][0] = 30;
matrix1[1][1] = 40;
matrix2[0][0] = 50;
matrix2[0][1] = 60;
matrix2[1][0] = 70;
matrix2[1][1] = 80;
System.out.println("Matrix 1 :"); for (int i = 0; i < matrix1.length; int colsize = matrix1[0].length; for (int j = 0; j < colsize; j++) System.out.print(m
}
System.out.println("Matrix 2 :"); i++) {
");
Output
Matrix 10 20
1 :
30 40
Matrix 50 60
70 80
Matrix 60 80
2 :
1 + Matrix 2 :
100 120
Our Tutorials Java Tutorials (introduction-to-java.php) Collection Tutorials (introduction-to-collection.php) JDBC Tutorials (jdbc-in-
java.php) C++ Tutorials (../cpp/introduction-to-cpp.php)
C++ Programs (../cpp-programs/cpp-programs.php) Java Programs (../java-programs/java-programs-example)
Tutorialscity 2016
(https://www.facebook.com/tutorialscityindia/) () (https://plus.google.com/u/0/108642049011677927484)
TutorialsCity (../index.php)
Home (../index.php) Core Java (introduction-to-java.php) Collection (introduction-to-collection.php) JDBC (jdbc-in-java.php)
Inheritence (inheritence-in-java.php)
Polymorphism (polymorphism-in-java.php)
Constructor (constructor-in-java.php)
String (what-is-string-in-java.php)
Swing (swing-in-java.php)
Collection (introduction-to-collection.php)
JDBC (jdbc-in-java.php)
nte
Interface in Java
Interface
Interface is blueprint of a class that is used to achieve fully abstraction also it supports multiple
inheritance. Interface is different from a abstract class because it contains only abstract methods.
There are mainly three reasons to use interface. They are given below.
Interface is used to achieve fully abstraction because it contains only abstract method.
In java Interface support multiple Inheritance because all the method in Interface are abstract .
it means derived class must need to implements all the method of interface so, there is no ambiguity
when we use interface because all the methods are implemented by derived class .
e.g. interface A and interface B contain same name method test then derived class must need to
implements test method in that case no ambiguity will arise.
interface Display {
void Display();
}
class InterfaceExample implements Display { public void Display() { System.out.println("Display method Called ..");
}
public static void main(String args[]) { InterfaceExample obj = new InterfaceExample(); obj.Display();
}
}
Output
Inteface in java
Interface Example
Interface Example
interface Display {
void Display();
}
class InterfaceExample implements Display { public void Display() { System.out.println("Display method Called ..");
}
public static void main(String args[]) { InterfaceExample obj = new InterfaceExample(); obj.Display();
}
}
Output
+ rollno);
Ouput
Student Name :Abhishek Roll no :1001
Our Tutorials Java Tutorials (introduction-to-java.php) Collection Tutorials (introduction-to-collection.php) JDBC Tutorials (jdbc-in-
java.php) C++ Tutorials (../cpp/introduction-to-cpp.php)
C++ Programs (../cpp-programs/cpp-programs.php) Java Programs (../java-programs/java-programs-example)
Tutorialscity 2016
(https://www.facebook.com/tutorialscityindia/) () (https://plus.google.com/u/0/108642049011677927484)
TutorialsCity (../index.php)
Home (../index.php) Core Java (introduction-to-java.php) Collection (introduction-to-collection.php) JDBC (jdbc-in-java.php)
Inheritence (inheritence-in-java.php)
Polymorphism (polymorphism-in-java.php)
Constructor (constructor-in-java.php)
String (what-is-string-in-java.php)
Swing (swing-in-java.php)
Collection (introduction-to-collection.php)
JDBC (jdbc-in-java.php)
An Abstract method is a method that does not contains any body so, it is a
incomplete method . An Abstract class is a class that contains some
abstract methods.
An Abstract class contains incomplete method so Java does not allowed to create a
object of abstract class. So for using it we need to create a sub class that extends the
abstract class and implements the abstract methods.
In java one way to achieve abstraction is abstract class(second way is using interface).
Abstract class does not provide 100% abstraction because it contain normal
method as well as abstract method
If Method is declared in a abstract class but method is not defined in a class (method
without body) known as abstract method.
The subclass will define the abstract method.
Abstract method can not be static and final. All the abstract methods of abstract
class must need to implement by child class.
Abstract class is used to achieve abstraction and Interfaces are used for the
same purpose but there is a difference between abstraction class and interface.
An abstract class have both normal function and abstract function but it must have at least abstract
method.
Abstract classes can have abstract methods, normal methods, member variables and
Constructors. We cannot create the object of Abstract classes it means it cannot be
instantiated.
All the abstract methods of abstract class must need to implement by child class.
Output
}
void balance() {
totalbalance = balance + interest;
System.out.println("Saving Account Total Balance " + totalbalance);
}
class Abstract_Class_Example extends BankAccount {
int balance;
int interest;
int totalbalance;
void createAccount(int
intial_balance) { balance =
intial_balance;
System.out.println("Current Account Intial Balance" + balance);
}
void interest() {
interest = balance * 6 / 100;
System.out.println("Current Account Interest " + interest);
}
void balance() {
totalbalance = balance + interest;
System.out.println("Current Account Total Balance " + totalbalance);
}
}
class test {
public static void main(String args[])
{ SavingAccount obj = new
SavingAccount(); obj.createAccount(10000);
obj.interest();
obj.balance();
Abstract_Class_Example obj1 = new Abstract_Class_Example();
obj1.createAccount(10000);
obj1.interest();
obj1.balance();
}
10600
Our Tutorials Java Tutorials (introduction-to-java.php) Collection Tutorials (introduction-to-collection.php) JDBC Tutorials (jdbc-in-
java.php) C++ Tutorials (../cpp/introduction-to-cpp.php)
C++ Programs (../cpp-programs/cpp-programs.php) Java Programs (../java-programs/java-programs-example)
Tutorialscity 2016
(https://www.facebook.com/tutorialscityindia/) () (https://plus.google.com/u/0/108642049011677927484)
TutorialsCity (../index.php)
Home (../index.php) Core Java (introduction-to-java.php) Collection (introduction-to-collection.php) JDBC (jdbc-in-java.php)
Inheritence (inheritence-in-java.php)
Polymorphism (polymorphism-in-java.php)
Constructor (constructor-in-java.php)
String (what-is-string-in-java.php)
Swing (swing-in-java.php)
Collection (introduction-to-collection.php)
JDBC (jdbc-in-java.php)
class InstanceIntializer{
int x,y,total;
InstanceIntializer(){ total=x+y;
System.out.println("X + Y = "+total);
}
{x=100;y=200;}
public static void main(String args[]){ InstanceIntializer b1=new InstanceIntializer(); InstanceIntializer b2=new InstanceIntializer();
}
Output
X + Y = 300 X + Y = 300
Rules for instance initializer block
class InstanceInitializer {
int x, y, total;
{
System.out.println("Instance Intializer called..");
}
public static void main(String a[]) { InstanceInitializer b1 = new InstanceInitializer(); InstanceInitializer b2 = new InstanceInitializer();
}
}
Output
Instance Initializer Or Constructor Or Base Class Constructor What Will Invoke First ?
class Base
Base() {
InstanceInitializer() {
System.out.println("Constructor called..");
}
}
Output
Base Class Constructor called.. Instance Intializer called..
Constructor called..
Our Tutorials Java Tutorials (introduction-to-java.php) Collection Tutorials (introduction-to-collection.php) JDBC Tutorials (jdbc-in-
java.php) C++ Tutorials (../cpp/introduction-to-cpp.php)
C++ Programs (../cpp-programs/cpp-programs.php) Java Programs (../java-programs/java-programs-example)
Tutorialscity 2016
(https://www.facebook.com/tutorialscityindia/) () (https://plus.google.com/u/0/108642049011677927484)
TutorialsCity (../index.php)
Home (../index.php) Core Java (introduction-to-java.php) Collection (introduction-to-collection.php) JDBC (jdbc-in-java.php)
Inheritence (inheritence-in-java.php)
Polymorphism (polymorphism-in-java.php)
Constructor (constructor-in-java.php)
String (what-is-string-in-java.php)
Swing (swing-in-java.php)
Collection (introduction-to-collection.php)
JDBC (jdbc-in-java.php)
A package represent a directory that contains a set of similar types of classes and Interfaces.
Package allows you to use same class name in different packages e.g. java.util have
Date class and java.sql also have Date class Because they are in different packages
(directory) so no conict will arise.
Package categorize the classes and interfaces by storing them in different directory.
e.g. type 1 classes in package 1 , type 2 classes package 2 etc.
1. Built In Packages
Built In Packages
Built In Packages are those packages which are already defined in java. Built In
Packages contains classes , interfaces and methods used to
perform specific task. eg java.util
,java.lang,java.io,javax.swing,java.awt, java.sql etc.
Our Tutorials Java Tutorials (introduction-to-java.php) Collection Tutorials (introduction-to-collection.php) JDBC Tutorials (jdbc-in-
java.php) C++ Tutorials (../cpp/introduction-to-cpp.php)
C++ Programs (../cpp-programs/cpp-programs.php) Java Programs (../java-programs/java-programs-example)
Tutorialscity 2016
(https://www.facebook.com/tutorialscityindia/) () (https://plus.google.com/u/0/108642049011677927484)
TutorialsCity (../index.php)
Home (../index.php) Core Java (introduction-to-java.php) Collection (introduction-to-collection.php) JDBC (jdbc-in-java.php)
Inheritence (inheritence-in-java.php)
Polymorphism (polymorphism-in-java.php)
Constructor (constructor-in-java.php)
String (what-is-string-in-java.php)
Swing (swing-in-java.php)
Collection (introduction-to-collection.php)
JDBC (jdbc-in-java.php)
Command Line Arguments are Arguments passed at Runtime of the program. Arguments are passed to
the main() method as an array of string.
You can convert the arguments to different data types by applying different predefined methods.
public class CommandLineArgument { public static void main(String[] args) { String name = args[0];
int age = Integer.parseInt(args[1]);
String course = args[2];
System.out.println("Student name : " + name + " Age : " + age + " Course : " + course);
}
}
Output
Tutorialscity 2016
(https://www.facebook.com/tutorialscityindia/) () (https://plus.google.com/u/0/108642049011677927484)
TutorialsCity (../index.php)
Home (../index.php) Core Java (introduction-to-java.php) Collection (introduction-to-collection.php) JDBC (jdbc-in-java.php)
String (what-is-string-in-java.php)
In Java (io-in-java.php)
Swing (swing-in-java.php)
Collection (introduction-to-collection.php)
JDBC (jdbc-in-java.php)
Coming Soon
Tutorialscity 2016
(https://www.facebook.com/tutorialscityindia/) () (https://plus.google.com/u/0/108642049011677927484)
TutorialsCity (../index.php)
Home (../index.php) Core Java (introduction-to-java.php) Collection (introduction-to-collection.php) JDBC (jdbc-in-java.php)
String (what-is-string-in-java.php)
In Java (io-in-java.php)
Swing (swing-in-java.php)
Collection (introduction-to-collection.php)
JDBC (jdbc-in-java.php)
Coming Soon
Tutorialscity 2016
(https://www.facebook.com/tutorialscityindia/) () (https://plus.google.com/u/0/108642049011677927484)
TutorialsCity (../index.php)
Home (../index.php) Core Java (introduction-to-java.php) Collection (introduction-to-collection.php) JDBC (jdbc-in-java.php)
String (what-is-string-in-java.php)
In Java (io-in-java.php)
Swing (swing-in-java.php)
Collection (introduction-to-collection.php)
JDBC (jdbc-in-java.php)
Coming Soon
Tutorialscity 2016
(https://www.facebook.com/tutorialscityindia/) () (https://plus.google.com/u/0/108642049011677927484)
TutorialsCity (../index.php)
Home (../index.php) Core Java (introduction-to-java.php) Collection (introduction-to-collection.php) JDBC (jdbc-in-java.php)
String (what-is-string-in-java.php)
In Java (io-in-java.php)
Swing (swing-in-java.php)
Collection (introduction-to-collection.php)
JDBC (jdbc-in-java.php)
Coming Soon
Tutorialscity 2016
(https://www.facebook.com/tutorialscityindia/) () (https://plus.google.com/u/0/108642049011677927484)
TutorialsCity (../index.php)
Home (../index.php) Core Java (introduction-to-java.php) Collection (introduction-to-collection.php) JDBC (jdbc-in-java.php)
Advantages-Of-OOPS (advantages-of-oops-in-java.php)
String (what-is-string-in-java.php)
MultiThreading (multithreading-in-java.php)
Swing (swing-in-java.php)
Collection (introduction-to-collection.php)
JDBC (jdbc-in-java.php)
In java exception handling is a mechanism to handle the runtime errors so that normal ow of the
application can not break.
What is error ?
An error is something that is incorrect eg a=b/0; is a incorrect statement.
Types of Errors
Checked exceptions are compile time exceptions because they are identied during the compile time of
program. e.g. File not found exception Is compile time exception because it is checked at compile time .
2. Unchecked exceptions
Checked exceptions are Run time exceptions because they are identied during the Run time of
program. e.g. Arithmetic exception e.g. a/b if b is 0 exception is occurred but it is a Run time exception
because it is checked at runtime.
Our Tutorials Java Tutorials (introduction-to-java.php) Collection Tutorials (introduction-to-collection.php) JDBC Tutorials (jdbc-in-
java.php) C++ Tutorials (../cpp/introduction-to-cpp.php)
C++ Programs (../cpp-programs/cpp-programs.php) Java Programs (../java-programs/java-programs-example)
Tutorialscity 2016
(https://www.facebook.com/tutorialscityindia/) () (https://plus.google.com/u/0/108642049011677927484)
TutorialsCity (../index.php)
Home (../index.php) Core Java (introduction-to-java.php) Collection (introduction-to-collection.php) JDBC (jdbc-in-java.php)
Advantages-Of-OOPS (advantages-of-oops-in-java.php)
String (what-is-string-in-java.php)
MultiThreading (multithreading-in-java.php)
Swing (swing-in-java.php)
Collection (introduction-to-collection.php)
JDBC (jdbc-in-java.php)
1. try
2. catch
3. throw
4. throws
5. finally
Exception Handling Mechanism
try{
//critical code of the program that might produce error
}catch
statement 1
Exception in thread "main" java.lang.ArithmeticException: / by zero at TryCatchExample.main(TryCatchExample.java:7)
Output of our program is statement 1 after that error occurred so we are not getting statement 2 and
statement n the reason is once error occurred in the program it will terminated . So without exception
handling if a error occurred in your program all the code after exception is not executed.
Output
Output: statement 1
java.lang.ArithmeticException: / by zero statement 2
statement n
Now it is clear from the above example that our code is executed even after error because exception is handled by catch block and our program is not term
and Statement n even after exception.
Our Tutorials Java Tutorials (introduction-to-java.php) Collection Tutorials (introduction-to-collection.php) JDBC Tutorials (jdbc-in-
java.php) C++ Tutorials (../cpp/introduction-to-cpp.php)
C++ Programs (../cpp-programs/cpp-programs.php) Java Programs (../java-programs/java-programs-example)
Tutorialscity 2016
(https://www.facebook.com/tutorialscityindia/) () (https://plus.google.com/u/0/108642049011677927484)
TutorialsCity (../index.php)
Home (../index.php) Core Java (introduction-to-java.php) Collection (introduction-to-collection.php) JDBC (jdbc-in-java.php)
Advantages-Of-OOPS (advantages-of-oops-in-java.php)
String (what-is-string-in-java.php)
MultiThreading (multithreading-in-java.php)
Swing (swing-in-java.php)
Collection (introduction-to-collection.php)
JDBC (jdbc-in-java.php)
Multiple catch blocks are used when a program generate more than one exception.
Each catch block handle a specific type of exception.
Syntax
try
{
//critical code of the program
}catch(ExceptionType1 e1) that may produce error
{
//handle type1 Exception
}catch(ExceptionType2 e2)
{
//handle type2 Exception
}catch(ExceptionType3 e3)
{
//handle type3 Exception
}
How it works :
Try block send the exception to rst catch block if it is exception type 1 then it is handled here if not
then it is matched with exception type 2 once exception will handled it will simply skip the other catch
blocks.
Output
statement 1 Arthematic Exception :
java.lang.ArithmeticException: / by zero statement 2
statement n
Important Point:
Make sure sub class exception always comes before the Base class Exception
i.e write FileNotFound Exception always before IO Exception
Our Tutorials Java Tutorials (introduction-to-java.php) Collection Tutorials (introduction-to-collection.php) JDBC Tutorials (jdbc-in-
java.php) C++ Tutorials (../cpp/introduction-to-cpp.php)
C++ Programs (../cpp-programs/cpp-programs.php) Java Programs (../java-programs/java-programs-example)
Tutorialscity 2016
(https://www.facebook.com/tutorialscityindia/) () (https://plus.google.com/u/0/108642049011677927484)
TutorialsCity (../index.php)
Home (../index.php) Core Java (introduction-to-java.php) Collection (introduction-to-collection.php) JDBC (jdbc-in-java.php)
Advantages-Of-OOPS (advantages-of-oops-in-java.php)
String (what-is-string-in-java.php)
MultiThreading (multithreading-in-java.php)
Swing (swing-in-java.php)
Collection (introduction-to-collection.php)
JDBC (jdbc-in-java.php)
e.g. suppose we have le reader program it opens the le and exception occurred and it is not handled
by any catch block in that case le is not closed because program terminated due to exception. It may
corrupt our file data to avoid such situation finally block is used. Finally block always executes no matter
whether exception occurred or not.
Important points about Finally Block
Finally block of code always executes no matter whether exception occurred or not.
In java finally block frequently used for cleanup-type activity.
A finally block always appears after the try and catch blocks .
try block can be used without catch block if you are using finally block.
public class FinallyBlockExample { public static void main(String args[]) { int value;
System.out.println("statement 1");
try {
value = 100 / 0; // may throw exception
} catch (Exception e) { System.out.println(" Exception Occured:"); System.out.println(e.toString());
} finally {
System.out.println("Code Inside Finally Block");
}
System.out.println("statement 2"); System.out.println("statement n");
}
}
Output
statement 1 Exception Occured:
java.lang.ArithmeticException: / by zero Code Inside Finally Block
statement 2
statement n
Our Tutorials Java Tutorials (introduction-to-java.php) Collection Tutorials (introduction-to-collection.php) JDBC Tutorials (jdbc-in-
java.php) C++ Tutorials (../cpp/introduction-to-cpp.php)
C++ Programs (../cpp-programs/cpp-programs.php) Java Programs (../java-programs/java-programs-example)
Tutorialscity 2016
(https://www.facebook.com/tutorialscityindia/) () (https://plus.google.com/u/0/108642049011677927484)
TutorialsCity (../index.php)
Home (../index.php) Core Java (introduction-to-java.php) Collection (introduction-to-collection.php) JDBC (jdbc-in-java.php)
Advantages-Of-OOPS (advantages-of-oops-in-java.php)
String (what-is-string-in-java.php)
MultiThreading (multithreading-in-java.php)
Swing (swing-in-java.php)
Collection (introduction-to-collection.php)
JDBC (jdbc-in-java.php)
Output
Exception in thread "main" java.lang.ArithmeticException: invalid mobile number at MobileNumberValidate.validate(MobileNumberValidate.java:4)
at MobileNumberValidate.main(MobileNumberValidate.java:9)
Our Tutorials Java Tutorials (introduction-to-java.php) Collection Tutorials (introduction-to-collection.php) JDBC Tutorials (jdbc-in-
java.php) C++ Tutorials (../cpp/introduction-to-cpp.php)
C++ Programs (../cpp-programs/cpp-programs.php) Java Programs (../java-programs/java-programs-example)
Tutorialscity 2016
(https://www.facebook.com/tutorialscityindia/) () (https://plus.google.com/u/0/108642049011677927484)
TutorialsCity (../index.php)
Home (../index.php) Core Java (introduction-to-java.php) Collection (introduction-to-collection.php) JDBC (jdbc-in-java.php)
Advantages-Of-OOPS (advantages-of-oops-in-java.php)
String (what-is-string-in-java.php)
MultiThreading (multithreading-in-java.php)
Swing (swing-in-java.php)
Collection (introduction-to-collection.php)
JDBC (jdbc-in-java.php)
Throw In Java
Throw
throw is used to throw exception explicitly it is written inside the try catch block .
throw is used for defining user defined exception.
Throw Example
class ThrowExample {
public void divide(int a, int b) throws ArithmeticException {
int c=a/b; System.out.println("a/b = "+c);
}
public static void main(String[] args) { ThrowExample obj=new ThrowExample(); obj.divide(30, 15);
obj.divide(30, 0);
}
}
Output
a/b = 2
Exception in thread "main" java.lang.ArithmeticException: / by zero at ThrowExample.divide(ThrowExample.java:3)
at ThrowExample.main(ThrowExample.java:10)
Throws
Throws keyword is used to declare an exception and used at time time of method declaration . no try
catch is required for using throws keyword.
Throw Example
class ThrowExample {
public void divide(int a, int b) {
if (b == 0)
throw new ArithmeticException("divisor should be > 0");
int c = a / b;
System.out.println("a/b = " +
c);
}
(https://www.facebook.com/tutorialscityindia/) () (https://plus.google.com/u/0/108642049011677927484)
TutorialsCity (../index.php)
Home (../index.php) Core Java (introduction-to-java.php) Collection (introduction-to-collection.php) JDBC (jdbc-in-java.php)
Advantages-Of-OOPS (advantages-of-oops-in-java.php)
String (what-is-string-in-java.php)
MultiThreading (multithreading-in-java.php)
Swing (swing-in-java.php)
Collection (introduction-to-collection.php)
JDBC (jdbc-in-java.php)
Final
final keyword is used to define constant in java. Once it is intialized with value we can not change it.
final indicate that you can assign value to varriable once then its set and can not be changed.
Finally
Finally keyword is used to execute code that need to be execute whether or not an exception occured or
not
Finalize
class FinalVarriableExample{
public static void main(String args[]){
class FinallyBlock{
public static void main(String args[]){
try{
int x=100/0;
}catch(Exception e){System.out.println(e);}
finally{System.out.println("finally block is executed");}
}
}
Output
java.lang.ArithmeticException: / by zero
finally block is executed
public static void main(String[] args) { FinalizeMethodExample obj1 = new FinalizeMethodExample(); FinalizeMethodExample obj2 = new FinalizeMethod
obj2 = null; System.gc();
}
}
Output
Tutorialscity 2016
(https://www.facebook.com/tutorialscityindia/) () (https://plus.google.com/u/0/108642049011677927484)
TutorialsCity (../index.php)
Home (../index.php) Core Java (introduction-to-java.php) Collection (introduction-to-collection.php) JDBC (jdbc-in-java.php)
What-is-String (what-is-string-in-java.php)
MultiThreading (multithreading-in-java.php)
Thread (join-method-in-thread.php)
Swing (swing-in-java.php)
Collection (introduction-to-collection.php)
JDBC (jdbc-in-java.php)
What Is Thread
What is thread
Threads are used in gaming and animation to perform multiple tasks at the same
time e.g. in Vice city user can drive a motor bike as well as user can shoot some
one. Without threads it is not possible.
3. Mobile application
Threads are used in mobile application to perform multiple task at the same time . e.g.
whatsapp allows you send some files to user 1 at the same time you can do chatting
with other users.
public void start() start a thread . Internally it invoke run() method to start thread.
public void run() this method contain actual action that need to perform by thread.
public int setPriority(int priority) used to set the priority of the thread.
public void sleep(long is used to pause thread for specified number of milliseconds.
milliseconds)
public void join() hold the other threads till the time specific thread not end.
public void join(long milliseconds) hold the other threads for specified milliseconds till the specific thread not
end.
Tutorialscity 2016
(https://www.facebook.com/tutorialscityindia/) ()
(https://plus.google.com/u/0/108642049011677927484)
TutorialsCity (../index.php)
Home (../index.php) Core Java (introduction-to-java.php) Collection (introduction-to-collection.php) JDBC (jdbc-in-java.php)
What-is-String (what-is-string-in-java.php)
MultiThreading (multithreading-in-java.php)
Thread (join-method-in-thread.php)
Swing (swing-in-java.php)
Collection (introduction-to-collection.php)
JDBC (jdbc-in-java.php)
1. New
2. Runnable
3. Running
4. Non-Runnable (Blocked)
5. Terminated
Life Cycle Of Thread
1. New
The thread is in new state when we create a object of Thread class . In new state memory is
allocated to thread but Thread is in inactive state means it is not started yet.
2) Runnable
To start the thread we need to invoke thread start method. when we call start method it
changed thread state from New to Runnable. All the Runnable Threads are available in
thread pool. Now it is in Runnable state not in running state, Now thread scheduler will
decide which thread needs to run from Thread pool.
3) Running
Thread scheduler pick one thread from runnable thread pool and change it`s state to
Running state and execute the thread.
4) Non-Runnable (Blocked)
A thread is in blocked or waiting state when it is waiting for some resource. e.g. waiting for input or Output , waiting for other thread to complete etc.
5) Terminated
A thread is in terminated state when
Our Tutorials Java Tutorials (introduction-to-java.php) Collection Tutorials (introduction-to-collection.php) JDBC Tutorials (jdbc-in-
java.php) C++ Tutorials (../cpp/introduction-to-cpp.php)
C++ Programs (../cpp-programs/cpp-programs.php) Java Programs (../java-programs/java-programs-example)
Tutorialscity 2016
(https://www.facebook.com/tutorialscityindia/) () (https://plus.google.com/u/0/108642049011677927484)
TutorialsCity (../index.php)
Home (../index.php) Core Java (introduction-to-java.php) Collection (introduction-to-collection.php) JDBC (jdbc-in-java.php)
What-is-String (what-is-string-in-java.php)
MultiThreading (multithreading-in-java.php)
Thread (join-method-in-thread.php)
Swing (swing-in-java.php)
Collection (introduction-to-collection.php)
JDBC (jdbc-in-java.php)
Thread In Java
Tutorialscity 2016
(https://www.facebook.com/tutorialscityindia/) () (https://plus.google.com/u/0/108642049011677927484)
TutorialsCity (../index.php)
Home (../index.php) Core Java (introduction-to-java.php) Collection (introduction-to-collection.php) JDBC (jdbc-in-java.php)
What-is-String (what-is-string-in-java.php)
MultiThreading (multithreading-in-java.php)
Thread (join-method-in-thread.php)
Swing (swing-in-java.php)
Collection (introduction-to-collection.php)
JDBC (jdbc-in-java.php)
Output
Our Tutorials Java Tutorials (introduction-to-java.php) Collection Tutorials (introduction-to-collection.php) JDBC Tutorials (jdbc-in-
java.php) C++ Tutorials (../cpp/introduction-to-cpp.php)
C++ Programs (../cpp-programs/cpp-programs.php) Java Programs (../java-programs/java-programs-example)
Tutorialscity 2016
(https://www.facebook.com/tutorialscityindia/) () (https://plus.google.com/u/0/108642049011677927484)
TutorialsCity (../index.php)
Home (../index.php) Core Java (introduction-to-java.php) Collection (introduction-to-collection.php) JDBC (jdbc-in-java.php)
What-is-String (what-is-string-in-java.php)
MultiThreading (multithreading-in-java.php)
Thread (join-method-in-thread.php)
Swing (swing-in-java.php)
Collection (introduction-to-collection.php)
JDBC (jdbc-in-java.php)
args[]) {
ThreadSleepExample t1 = new ThreadSleepExample(); ThreadSleepExample t2 = new ThreadSleepExample(); t1.start();
t2.start();
}
}
Output
Output:
0
0
Tutorialscity 2016
(https://www.facebook.com/tutorialscityindia/) () (https://plus.google.com/u/0/108642049011677927484)
TutorialsCity (../index.php)
Home (../index.php) Core Java (introduction-to-java.php) Collection (introduction-to-collection.php) JDBC (jdbc-in-java.php)
What-is-String (what-is-string-in-java.php)
MultiThreading (multithreading-in-java.php)
Thread (join-method-in-thread.php)
Swing (swing-in-java.php)
Collection (introduction-to-collection.php)
JDBC (jdbc-in-java.php)
Thread Scheduler run the thread from thread pool So , order of Thread execution is
decided by Thread Scheduler . But if you use join() method it instruct the thread to wait
untill currently thread which called the join method not completed.
Join() Constructors
public void join() hold the other threads till the time specific thread not end.
public void join(long milliseconds) hold the other threads for specified milliseconds till the specific thread not
end.
Thread Sleep Method In Java
+ i);
}
public static void main(String args[]) throws
Exception { Thread t1 = new Thread(new
ThreadJoinExample()); Thread t2 = new
Thread(new ThreadJoinExample()); Thread t3 =
new Thread(new ThreadJoinExample()); t1.start();
t1.join();
t2.start();
t3.start();
}
Output
Threa Name Thread status tru value
d = -0 = e =1
Threa Name Thread status tru value
d = -0 = e =2
Threa Name Thread status tru value
d = -0 = e =3
Threa Name Thread status tru value
d = -0 = e =4
Threa Name Thread status tru value
d = -0 = e =5
Threa Name Thread status tru value
d = -1 = e =1
Threa Name Thread status tru value
d = -2 = e =1
Threa Name Thread status tru value
d = -2 = e =2
Threa Name Thread status tru value
d = -1 = e =2
Threa Name Thread status tru value
d = -1 = e =3
Threa Name Thread status tru value
d = -2 = e =3
Threa Name Thread status tru value
d = -2 = e =4
Threa Name Thread status tru value
d = -1 = e =4
Threa Name Thread status tru value
d = -2 = e =5
Threa Name Thread status tru value
d = -1 = e =5
Output
Threa Name Thread- status true value
d = 0 = =1
Threa Name Thread- status true value
d = 0 = =2
Threa Name Thread- status true value
d = 0 = =3
Threa Name Thread- status true value
d = 0 = =4
Threa Name Thread- status true value
d = 0 = =5
Threa Name Thread- status true value
d = 1 = =1
Threa Name Thread- status true value
d = 2 = =1
Threa Name Thread- status true value
d = 2 = =2
Threa Name Thread- status true value
d = 1 = =2
Threa Name Thread- status true value
d = 1 = =3
Threa Name Thread- status true value
d = 2 = =3
Threa Name Thread- status true value
d = 2 = =4
Threa Name Thread- status true value
d = 1 = =4
Threa Name Thread- status true value
d = 2 = =5
Threa Name Thread- status true value
d = 1 = =5
Our Tutorials Java Tutorials (introduction-to-java.php) Collection Tutorials (introduction-to-collection.php) JDBC Tutorials (jdbc-in-
java.php) C++ Tutorials (../cpp/introduction-to-cpp.php)
C++ Programs (../cpp-programs/cpp-programs.php) Java Programs (../java-programs/java-programs-example)
Tutorialscity 2016
(https://www.facebook.com/tutorialscityindia/) () (https://plus.google.com/u/0/108642049011677927484)
TutorialsCity (../index.php)
Home (../index.php) Core Java (introduction-to-java.php) Collection (introduction-to-collection.php) JDBC (jdbc-in-java.php)
What-is-String (what-is-string-in-java.php)
MultiThreading (multithreading-in-java.php)
Thread (join-method-in-thread.php)
Swing (swing-in-java.php)
Collection (introduction-to-collection.php)
JDBC (jdbc-in-java.php)
In java sleep() method is used to pause thread for specied number of milliseconds given in the
argument.
args[]) {
ThreadSleepExample t1 = new ThreadSleepExample(); ThreadSleepExample t2 = new ThreadSleepExample(); t1.start();
t2.start();
}
}
Output
Output:
0
0
Tutorialscity 2016
(https://www.facebook.com/tutorialscityindia/) () (https://plus.google.com/u/0/108642049011677927484)
TutorialsCity (../index.php)
Home (../index.php) Core Java (introduction-to-java.php) Collection (introduction-to-collection.php) JDBC (jdbc-in-java.php)
Swing (swing-in-java.php)
Swing Introduction (swing-in-java.php)
JButton (jbutton-in-java-swing.php)
JRadioButton (jradiobutton-in-java-swing.php)
JTextArea (jtextarea-in-java-swing.php)
JComboBox (jcombobox-in-java-swing.php)
Collection (introduction-to-collection.php)
JDBC (jdbc-in-java.php)
There are two ways for reading a file in java given below:
1. By Byte Stream
InputStream
BufferedInputStream
2. By Character Stream
FileReader
BufferedRead
er
By Byte Stream
In this method we use the byte stream to read the data from the file.
InputStream and BufferedInputStream use the byte stream to read the data from the file.
By CharacterStream
In this method we use the Character stream to read the data from the file.
FileReader and BufferedReader used the Character Stream to read the data from the file.
1. By Byte Stream
OutputStream
BufferedOutputStream
2. By Character Stream
FileWriter
BufferedWrite
r
By Byte Stream
In this method we use the byte stream to write the data to the file.
InputStream and BufferedInputStream use the byte stream to write the data to the file.
By CharacterStream
In this method we use the Character stream to write the data to the file.
FileReader and BufferedReader used the Character stream to read the data to the file.
Our Tutorials Java Tutorials (introduction-to-java.php) Collection Tutorials (introduction-to-collection.php) JDBC Tutorials (jdbc-in-
java.php) C++ Tutorials (../cpp/introduction-to-cpp.php)
C++ Programs (../cpp-programs/cpp-programs.php) Java Programs (../java-programs/java-programs-example)
Tutorialscity 2016
(https://www.facebook.com/tutorialscityindia/) () (https://plus.google.com/u/0/108642049011677927484)
TutorialsCity (../index.php)
Home (../index.php) Core Java (introduction-to-java.php) Collection (introduction-to-collection.php) JDBC (jdbc-in-java.php)
Swing (swing-in-java.php)
Swing Introduction (swing-in-java.php)
JButton (jbutton-in-java-swing.php)
JRadioButton (jradiobutton-in-java-swing.php)
JTextArea (jtextarea-in-java-swing.php)
JComboBox (jcombobox-in-java-swing.php)
Collection (introduction-to-collection.php)
JDBC (jdbc-in-java.php)
BufferedInputStream
BufferedInputStream also use the byte stream to read the data from the file.
Output
FILE
OUTPUT
Done...
BufferedOutputStream
BufferedOutputStream also use the byte stream to write the data to the file.
Output
Done...
Tutorialscity 2016
(https://www.facebook.com/tutorialscityindia/) () (https://plus.google.com/u/0/108642049011677927484)
TutorialsCity (../index.php)
Home (../index.php) Core Java (introduction-to-java.php) Collection (introduction-to-collection.php) JDBC (jdbc-in-java.php)
Swing (swing-in-java.php)
Swing Introduction (swing-in-java.php)
JButton (jbutton-in-java-swing.php)
JRadioButton (jradiobutton-in-java-swing.php)
JTextArea (jtextarea-in-java-swing.php)
JComboBox (jcombobox-in-java-swing.php)
Collection (introduction-to-collection.php)
JDBC (jdbc-in-java.php)
File Input Stream is used raw bytes from files. It can read 8 bit (1 byte) at a time.
It is bit slower i.e. if you want to read a file that contain 1000 lines and 1000 lines
contain 1,00,000 character in that case you need to repeat loop for 1,00,000 times
in order to print all data. So, it takes time . On the other hand through buffer
reader you can read line by line so instead of repeating loop for 1,00,000 times
you need to repeat it for 1000 times only.
Output
FileOutput Stream is used to write data to file it write small amount of data to
file. Because of that reason file writer is slow.
Write Data using File Writer
import java.io.*;
class Example {
public static void main(String args[]) {
try {
FileWriter fis = new FileWriter("file.txt");
BufferedWriter bis = new
BufferedWriter(fis);
String data = "Buffered Input Stream Example data";
bis.write(data);
System.out.println("Done...
"); bis.close();
fis.close();
} catch (Exception e)
{ System.out.println(e);
}
Output
Done...
Tutorialscity 2016
(https://www.facebook.com/tutorialscityindia/) () (https://plus.google.com/u/0/108642049011677927484)
TutorialsCity (../index.php)
Home (../index.php) Core Java (introduction-to-java.php) Collection (introduction-to-collection.php) JDBC (jdbc-in-java.php)
Swing (swing-in-java.php)
Swing Introduction (swing-in-java.php)
JButton (jbutton-in-java-swing.php)
JRadioButton (jradiobutton-in-java-swing.php)
JTextArea (jtextarea-in-java-swing.php)
JComboBox (jcombobox-in-java-swing.php)
Collection (introduction-to-collection.php)
JDBC (jdbc-in-java.php)
class FileInputStreamExample{
}
}
FileOutputStream-
class FileOutputStreamExample{
Our Tutorials Java Tutorials (introduction-to-java.php) Collection Tutorials (introduction-to-collection.php) JDBC Tutorials (jdbc-in-
java.php) C++ Tutorials (../cpp/introduction-to-cpp.php)
C++ Programs (../cpp-programs/cpp-programs.php) Java Programs (../java-programs/java-programs-example)
Tutorialscity 2016
(https://www.facebook.com/tutorialscityindia/) ()
(https://plus.google.com/u/0/108642049011677927484)
TutorialsCity (../index.php)
Home (../index.php) Core Java (introduction-to-java.php) Collection (introduction-to-collection.php) JDBC (jdbc-in-java.php)
Swing (swing-in-java.php)
Swing Introduction (swing-in-java.php)
JButton (jbutton-in-java-swing.php)
JRadioButton (jradiobutton-in-java-swing.php)
JTextArea (jtextarea-in-java-swing.php)
JComboBox (jcombobox-in-java-swing.php)
Collection (introduction-to-collection.php)
JDBC (jdbc-in-java.php)
Buffer Reader
eg you tube working on same concept before playing video it store some buffer till the time you saw that part
next part in buffer ready. So in case of files it can read more than one char it store it in the buffer and save the
time.
Output
Buffer writer
import java.io.*;
class Example {
public static void main(String args[]) {
try {
FileWriter fis = new FileWriter("file.txt"); BufferedWriter bis = new BufferedWriter(fis);
String data = "Buffered Input Stream Example data"; bis.write(data);
System.out.println("Done..."); bis.close();
fis.close();
} catch (Exception e) { System.out.println(e);
}
}
}
Our Tutorials Java Tutorials (introduction-to-java.php) Collection Tutorials (introduction-to-collection.php) JDBC Tutorials (jdbc-in-
java.php) C++ Tutorials (../cpp/introduction-to-cpp.php)
C++ Programs (../cpp-programs/cpp-programs.php) Java Programs (../java-programs/java-programs-example)
Tutorialscity 2016
(https://www.facebook.com/tutorialscityindia/) () (https://plus.google.com/u/0/108642049011677927484)
TutorialsCity (../index.php)
Home (../index.php) Core Java (introduction-to-java.php) Collection (introduction-to-collection.php) JDBC (jdbc-in-java.php)
Swing (swing-in-java.php)
Swing Introduction (swing-in-java.php)
JButton (jbutton-in-java-swing.php)
JRadioButton (jradiobutton-in-java-swing.php)
JTextArea (jtextarea-in-java-swing.php)
JComboBox (jcombobox-in-java-swing.php)
Collection (introduction-to-collection.php)
JDBC (jdbc-in-java.php)
Input Output In
(https://www.facebook.com/tutorialscityindia/) () (https://plus.google.com/u/0/108642049011677927484)
TutorialsCity (../index.php)
Home Core Java C C++ SQL HTML Java Interview Question C++ Interview Question
)
) )
Swing (swing-in-java.php)
HashSet (hash-set-in-collection.php)
LinkedHashSet (linkedhashset-in-collection.php)
hashtable (hashtable-in-collection.php)
HashMap (hashmap-in-collection.php)
TreeMap (treemap-in-collection.php)
LinkedHashMap (linkedhashmap-in-collection.php)
JDBC (jdbc-in-java.php)
Java Swing
Introduction To Swing
In Java swing is a tool-kit that used to create Graphical User Interface for a application.
Java swing is a part of the Java Foundation Classes(JFC) that is an API used for
creating graphical user interface for Java Application.
Java swing is completely written in Java. So it fast , platform independent and lightweight as
compare to AWT.
Our Tutorials Java Tutorials (introduction-to-java.php) Collection Tutorials (introduction-to-collection.php) JDBC Tutorials (jdbc-in-
java.php) C++ Tutorials (../cpp/introduction-to-cpp.php)
C++ Programs (../cpp-programs/cpp-programs.php) Java Programs (../java-programs/java-programs-example)
Tutorialscity 2016
(https://www.facebook.com/tutorialscityindia/) () (https://plus.google.com/u/0/108642049011677927484)
TutorialsCity (../index.php)
Home Core Java C C++ SQL HTML Java Interview Question C++ Interview Question
)
) )
JButton (jbutton-in-java-swing.php)
Vector (vector-in-collection.php)
HashSet (hash-set-in-collection.php)
LinkedHashSet (linkedhashset-in-collection.php)
hashtable (hashtable-in-collection.php)
HashMap (hashmap-in-collection.php)
TreeMap (treemap-in-collection.php)
LinkedHashMap (linkedhashmap-in-collection.php)
JDBC (jdbc-in-java.php)
JButton in Java
The JButton class is used to create a button that generate a event when it is pressed.
Types of JButton in Java:
2. Button(Icon pathOfIcon)- used to Creates a button with an icon specified in the argument.
3. JButton(String tittle)- used to Creates a button with tittle given in the argument.
4. JButton(String tittle, Icon iconPath)- used to Creates a button with tittle and an icon.
3. public void setEnabled(boolean flag)- used to Creates a button with title given in the argument.
4. JButton(String tittle, Icon iconPath)- used to Creates a button with title and an icon.
5. public void setIcon(Icon iconPath)- is used to set the Icon on the button.
7. public void addActionListener(ActionListener e)- is used to perform action when a event is generated
JButton Program
import javax.swing.*; //importing java swing class
Output
Prev (swing-in-java.php) Next (jradiobutton-in-java-swing.php)
Our Tutorials Java Tutorials (introduction-to-java.php) Collection Tutorials (introduction-to-collection.php) JDBC Tutorials (jdbc-in-
java.php) C++ Tutorials (../cpp/introduction-to-cpp.php)
C++ Programs (../cpp-programs/cpp-programs.php) Java Programs (../java-programs/java-programs-example)
Tutorialscity 2016
(https://www.facebook.com/tutorialscityindia/) ()
(https://plus.google.com/u/0/108642049011677927484)
TutorialsCity (../index.php)
Home Core Java C C++ SQL HTML Java Interview Question C++ Interview Question
)
) )
JRadioButton (jradiobutton-in-java-swing.php)
Vector (vector-in-collection.php)
HashSet (hash-set-in-collection.php)
LinkedHashSet (linkedhashset-in-collection.php)
hashtable (hashtable-in-collection.php)
HashMap (hashmap-in-collection.php)
TreeMap (treemap-in-collection.php)
LinkedHashMap (linkedhashmap-in-collection.php)
JDBC (jdbc-in-java.php)
JRadioButton In Java
JRadioButton
JRadioButton is a component which allows you to choose one option from multiple options.
It is most commonly used for selecting sex eg male or female on social network
sites or in quiz where you have to choose one option from multiple options.
By default it allows mutiple selectiion if you want to allows one selection only for this you need to
add in ButtonGroup to select one radio button.
JRadioButton Methods
new JRadiobuttonExample();
}
}
Output
ButtonGroup In Java
The ButtonGroup class allows only one button selection at a time from a group multiple buttons.
// JRadiobuttonExample constructor
new JRadiobuttonExample();
}
Output
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
public class JRadiobuttonExample implements
ActionListener { JFrame frame;
JRadioButton
radioButton1;
JRadioButton
radioButton2; JButton
button;
JRadiobuttonExample() {
frame = new JFrame();// creating instance of JFrame
// JRadiobuttonExample constructor
new JRadiobuttonExample();
@Override
if (radioButton1.isSelected())
else if (radioButton2.isSelected())
JOptionPane.showMessageDialog(null, "Female Radio Button Selected");
else
JOptionPane.showMessageDialog(null,"Please Select atleat one option");
Output
Prev (jbutton-in-java-swing.php) Next (jtextarea-in-java-swing.php)
Our Tutorials Java Tutorials (introduction-to-java.php) Collection Tutorials (introduction-to-collection.php) JDBC Tutorials (jdbc-in-
java.php) C++ Tutorials (../cpp/introduction-to-cpp.php)
C++ Programs (../cpp-programs/cpp-programs.php) Java Programs (../java-programs/java-programs-example)
Tutorialscity 2016
(https://www.facebook.com/tutorialscityindia/) () (https://plus.google.com/u/0/108642049011677927484)
TutorialsCity (../index.php)
Home Core Java C C++ SQL HTML Java Interview Question C++ Interview Question
)
) )
JTextArea (jtextarea-in-java-swing.php)
Vector (vector-in-collection.php)
HashSet (hash-set-in-collection.php)
LinkedHashSet (linkedhashset-in-collection.php)
hashtable (hashtable-in-collection.php)
HashMap (hashmap-in-collection.php)
TreeMap (treemap-in-collection.php)
LinkedHashMap (linkedhashmap-in-collection.php)
JDBC (jdbc-in-java.php)
What is JTextArea
2. JTextArea(String text): used to create a text area with initial text specified in the argument.
3. JTextArea(int rows, int columns): creates a text area with the fixed number of
4. JTextArea(String text, int row, int column): used creates a text area with fixed number
of rows and columns specified in the arguments as rows and columns with initial text
3. public void insert(String text, int pos): is used to insert the text specified in the
argument on the specified position.
4. public void setFont(Font f): is used to set the font type of text area.
5. public void append(String text): is used to append the specified text to the end of the document.
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
public class JTextAreaExample implements
ActionListener { JFrame frame;
JTextArea text;
JButton button;
JTextAreaExampl
e() {
frame = new JFrame();// creating instance of JFrame
// creating instance of
JRdioButton text = new
JTextArea();
text.setBounds(60, 110, 200,
70); button = new
JButton("click");
// defining button position and width,
height button.setBounds(60, 200, 80,
30); frame.add(text);// adding button in
JFrame frame.add(button);
frame.setSize(500, 400);// set the frame width 400px and height
500px frame.setLayout(null);
frame.setVisible(true); // display The JFrame
// exit the frame when close button pressed
button.addActionListener(this);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CL
OSE);
}
// JRadiobuttonExample constructor
new JTextAreaExample();
@Override
public void actionPerformed(ActionEvent arg0) {
// TODO Auto-generated method stub text.setText("Data Fo Text Box");
}
}
Output
Our Tutorials Java Tutorials (introduction-to-java.php) Collection Tutorials (introduction-to-collection.php) JDBC Tutorials (jdbc-in-
java.php) C++ Tutorials (../cpp/introduction-to-cpp.php)
C++ Programs (../cpp-programs/cpp-programs.php) Java Programs (../java-programs/java-programs-example)
Tutorialscity 2016
(https://www.facebook.com/tutorialscityindia/) () (https://plus.google.com/u/0/108642049011677927484)
TutorialsCity (../index.php)
Home Core Java C C++ SQL HTML Java Interview Question C++ Interview Question
)
) )
JComboBox (jcombobox-in-java-swing.php)
Vector (vector-in-collection.php)
HashSet (hash-set-in-collection.php)
LinkedHashSet (linkedhashset-in-collection.php)
hashtable (hashtable-in-collection.php)
HashMap (hashmap-in-collection.php)
TreeMap (treemap-in-collection.php)
LinkedHashMap (linkedhashmap-in-collection.php)
JDBC (jdbc-in-java.php)
JComboBox
What Is JComboBox
JComboBox Methods
heigh
Output
JcomboBox example with action listner
// JComboBoxExample constructor
new JComboBoxExample();
}
@Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
String value = combobox.getSelectedItem().toString(); JOptionPane.showMessageDialog(null, value
+ " is selected from combo box");
}
Output
Prev (jtextarea-in-java-swing.php) Next (introduction-to-collection.php)
Our Tutorials Java Tutorials (introduction-to-java.php) Collection Tutorials (introduction-to-collection.php) JDBC Tutorials (jdbc-in-
java.php) C++ Tutorials (../cpp/introduction-to-cpp.php)
C++ Programs (../cpp-programs/cpp-programs.php) Java Programs (../java-programs/java-programs-example)
Tutorialscity 2016
(https://www.facebook.com/tutorialscityindia/) ()
(https://plus.google.com/u/0/108642049011677927484)
TutorialsCity (../index.php)
Home (../index.php) Core Java (introduction-to-java.php) Collection (introduction-to-collection.php) JDBC (jdbc-in-java.php)
)
) )
ArrayList (arraylist-in-collection.php)
HashMap (hashmap-in-collection.php)
TreeMap (treemap-in-collection.php)
LinkedHashMap (linkedhashmap-in-collection.php)
JDBC (jdbc-in-java.php)
ArrayList In Java
ArrayList In Java
Java ArrayList is similar to array but it modify its size at run time so we can say it a
dynamic array. Dynamic array means it can grow and shrink size of array at run time
and static array means size of array is initialized at compile time.
ArrayList In Java
Array list can extends its size at run time and static array cannot extends at
run time. Java ArrayList can store duplicate elements.
Java ArrayList store the elements in the same order in which inserted ( in
Sequence eg element 1 at first location element 2 at second location)
In Java ArrayList Index is used to access element so , random access is possible in array list.
Disadvantage Of ArrayList
The main disadvantage of array list is Slow manipulation because for inserting a
element at a particular location a lot of elements need to shift up and deleting a
element in Arraylist a lot of elements need to be shift up.
import java.util.*;
class ArrayListExample {
public static void main(String args[]) { ArrayList student = new ArrayList(); student.add("Vinay"); student.add("Ankita"); student.add("Abhishek");
for (int i = 0; i < student.size(); i++) { System.out.println(student.get(i));
}
}
}
Output
import java.util.*;
class ArrayListExample {
public static void main(String args[]) { ArrayList student = new ArrayList(); student.add("Vinay"); student.add("Ankita"); student.add("Abhishek");
for (int i = 0; i < student.size(); i++) { System.out.println(student.get(i));
}
}
}
Output
import java.util.*;
class ArrayListExample {
public static void main(String args[]) { ArrayList names = new ArrayList(); names.add("Rahul");
names.add("Kamal"); names.add("Abhishek"); for (String s:names) { System.out.println(s);
}
}
}
Output
import java.util.*;
class ArrayListExample {
public static void main(String args[]) { ArrayList al = new ArrayList(); al.add("rishab");
al.add("jot");
al.add("aman");
al.add("yury"); Collections.sort(al); for(String a:al) System.out.println(a);
}
}
Output
import java.util.*;
class ArrayListExample {
public static void main(String args[]) { ArrayList al = new ArrayList(); al.add("rishab");
al.add("jot");
al.add("aman");
al.add("yury");
al.add(0,"New name"); for(String a:al) System.out.println(a);
}
}
Output
class ArrayListExample {
al.add("yury");
al.remove(0);
for(String a:al)
System.out.println(a);
}
Output
jot
aman
yury
Tutorialscity 2016
(https://www.facebook.com/tutorialscityindia/) () (https://plus.google.com/u/0/108642049011677927484)
TutorialsCity (../index.php)
Home (../index.php) Core Java (introduction-to-java.php) Collection (introduction-to-collection.php) JDBC (jdbc-in-java.php)
)
) )
LinkList (linklist-in-collection.php)
HashMap (hashmap-in-collection.php)
TreeMap (treemap-in-collection.php)
LinkedHashMap (linkedhashmap-in-collection.php)
JDBC (jdbc-in-java.php)
LinkedList In Java
LinkedList
Java LinkedList class is a implementation of List Interface and it store elements in
doubly linked list. Java LinkedList class can contain duplicate elements.
Java LinkList maintain the insertion order it means elements stored in the
same order in which inserted ( in Sequence e.g. element 1 at first location
element 2 at second location)
The main advantage of Link list is fast manipulation because for inserting and deleting a
element at a particular no shifting is required.
The main disadvantage of Link list is that sequential traversing. Because each
node contains the address of next node to in order to access a particular node
we need to access all previous nodes.
}
}
Output
for(String a:names)
System.out.println(a);
}
}
Output
Rishab jot
john
Output
Rishab
jot john
Output
Output
class LinkedListExample {
names.add("yury");
Collections.sort(nam
es); for(String
a:names)
System.out.println(a)
;
}
}
Output
aman
jot
rishab
yury
Prev (arraylist-in-collection.php) Next (vector-in-collection.php)
Our Tutorials Java Tutorials (introduction-to-java.php) Collection Tutorials (introduction-to-collection.php) JDBC Tutorials (jdbc-in-
java.php) C++ Tutorials (../cpp/introduction-to-cpp.php)
C++ Programs (../cpp-programs/cpp-programs.php) Java Programs (../java-programs/java-programs-example)
Tutorialscity 2016
(https://www.facebook.com/tutorialscityindia/) () (https://plus.google.com/u/0/108642049011677927484)
TutorialsCity (../index.php)
Home (../index.php) Core Java (introduction-to-java.php) Collection (introduction-to-collection.php) JDBC (jdbc-in-java.php)
)
) )
Vector (vector-in-collection.php)
HashMap (hashmap-in-collection.php)
TreeMap (treemap-in-collection.php)
LinkedHashMap (linkedhashmap-in-collection.php)
JDBC (jdbc-in-java.php)
Vector In Java
Vector
Vector use array as a backend like ArrayList but vector is different from ArrayList
because of three main reasons:
synchroniz
ed Growth
size Speed
Synchronized
synchronized means only one resource can access the shared resource at a time .
Growth size
Vector and ArraList both expends its size at Runtime if it is run out
of memory . Vector expends the size by 100% but ArrayList
expends the size by 50%.
Speed
Vectors are synchronized it means shared resource can not be accessed by multiple
threads at the same time Because of this it is slow as compare to ArrayList.
vl.add("Nitish");
Output
Kaanu
Abhi
Preet
Pal
Nitish
Tutorialscity 2016
(https://www.facebook.com/tutorialscityindia/) () (https://plus.google.com/u/0/108642049011677927484)
TutorialsCity (../index.php)
Home (../index.php) Core Java (introduction-to-java.php) Collection (introduction-to-collection.php) JDBC (jdbc-in-java.php)
)
) )
HashSet (hash-set-in-collection.php)
HashMap (hashmap-in-collection.php)
TreeMap (treemap-in-collection.php)
LinkedHashMap (linkedhashmap-in-collection.php)
JDBC (jdbc-in-java.php)
HashSet In Java
HashSet
HashSet uses the hash table store its elements .Hah set does not maintain the
insertion order it means it order the data in the order in which they were
inserted.
+ iterator.next());
Output
Student name :Ankita
Student name :Vinay Student name :Abhi
Our Tutorials Java Tutorials (introduction-to-java.php) Collection Tutorials (introduction-to-collection.php) JDBC Tutorials (jdbc-in-
java.php) C++ Tutorials (../cpp/introduction-to-cpp.php)
C++ Programs (../cpp-programs/cpp-programs.php) Java Programs (../java-programs/java-programs-example)
Tutorialscity 2016
(https://www.facebook.com/tutorialscityindia/) () (https://plus.google.com/u/0/108642049011677927484)
TutorialsCity (../index.php)
Home (../index.php) Core Java (introduction-to-java.php) Collection (introduction-to-collection.php) JDBC (jdbc-in-java.php)
)
) )
LinkedHashSet (linkedhashset-in-collection.php)
HashMap (hashmap-in-collection.php)
TreeMap (treemap-in-collection.php)
LinkedHashMap (linkedhashmap-in-collection.php)
JDBC (jdbc-in-java.php)
LinkedHashSet In Java
LinkHashset
LinkedHashSet uses the hash table which internally uses linked list to maintain the
Insertion order (maintain the elements order based on the order in which they were
inserted).LinkHashset has average performance it is slower than HashSet but faster
than LinkHashset.
import java.util.*;
class LinkedHashSetExample { publicstaticvoid main(String args[]) {
LinkedHashSetstudent = new LinkedHashSet(); student.add("Abhi");
student.add("Vinay"); student.add("Ankita"); student.add("Vinay"); Iteratoriterator = student.iterator(); while (iterator.hasNext()) {
System.out.println("Student name :" + iterator.next());
}
}
}
Output
Tutorialscity 2016
(https://www.facebook.com/tutorialscityindia/) () (https://plus.google.com/u/0/108642049011677927484)
TutorialsCity (../index.php)
Home (../index.php) Core Java (introduction-to-java.php) Collection (introduction-to-collection.php) JDBC (jdbc-in-java.php)
)
) )
hashtable (hashtable-in-collection.php)
HashMap (hashmap-in-collection.php)
TreeMap (treemap-in-collection.php)
LinkedHashMap (linkedhashmap-in-collection.php)
JDBC (jdbc-in-java.php)
Hashtable In Java
Hashtable
A Hashtable similar to array. Hash table use key value pair. In hastable we use key as
a index to get value from a specified position.
It cannot contain duplicate
elements. It does not allow null
key or value.
It is synchronized it means only one thread can update the hashtable at a time.
Each thread takes a lock before update operation and release the lock once
updation done.
HashTable Example
Import Java.util.*;
class HashTableExample { publicstaticvoid main(String args[]) { Hashtablestudent = new Hashtable(); student.put(1001, "Vinay"); student.put(1002, "Ankita");
for (Map.Entrym : student.entrySet()) { System.out.println(m.getKey() + " " + m.getValue());
}
}
}
Output
1003 Abhishek
1002 Ankita
1001 Vinay
Our Tutorials Java Tutorials (introduction-to-java.php) Collection Tutorials (introduction-to-collection.php) JDBC Tutorials (jdbc-in-
java.php) C++ Tutorials (../cpp/introduction-to-cpp.php)
C++ Programs (../cpp-programs/cpp-programs.php) Java Programs (../java-programs/java-programs-example)
Tutorialscity 2016
(https://www.facebook.com/tutorialscityindia/) () (https://plus.google.com/u/0/108642049011677927484)
TutorialsCity (../index.php)
Home (../index.php) Core Java (introduction-to-java.php) Collection (introduction-to-collection.php) JDBC (jdbc-in-java.php)
)
) )
HashMap (hashmap-in-collection.php)
TreeMap (treemap-in-collection.php)
LinkedHashMap (linkedhashmap-in-collection.php)
JDBC (jdbc-in-java.php)
It does not maintain the order of data it means it does not store the data in the same order in
which they are inserted.
It is not synchronized it means multiple threads can update values at the same time
HashMap Example
Output
1001 Vinay
1002 Ankita
1003 Abhishek
Our Tutorials Java Tutorials (introduction-to-java.php) Collection Tutorials (introduction-to-collection.php) JDBC Tutorials (jdbc-in-
java.php) C++ Tutorials (../cpp/introduction-to-cpp.php)
C++ Programs (../cpp-programs/cpp-programs.php) Java Programs (../java-programs/java-programs-example)
Tutorialscity 2016
(https://www.facebook.com/tutorialscityindia/) () (https://plus.google.com/u/0/108642049011677927484)
TutorialsCity (../index.php)
Home (../index.php) Core Java (introduction-to-java.php) Collection (introduction-to-collection.php) JDBC (jdbc-in-java.php)
)
) )
HashMap (hashmap-in-collection.php)
TreeMap (treemap-in-collection.php)
LinkedHashMap (linkedhashmap-in-collection.php)
JDBC (jdbc-in-java.php)
TreeMap In Java
TreeMap
A TreeMap contains key - value pair each key is associated with value. It
contains only unique elements.
It cannot have null key but can have multiple
null values. Tree set store data in ascending
order.
Tre e MapExample
import java.util.*;
class TreeMapExample {
public static void main(String args[]) { TreeMap student = new TreeMap(); student.put(1001, "Vinay"); student.put(1002, "Ankita"); student.put(1003, "Abhishek
for (Map.Entry m : student.entrySet()) { System.out.println(m.getKey() + " " + m.getValue());
}
}
}
Output
1001 Vinay
1002 Ankita
1003 Abhishek
Our Tutorials Java Tutorials (introduction-to-java.php) Collection Tutorials (introduction-to-collection.php) JDBC Tutorials (jdbc-in-
java.php) C++ Tutorials (../cpp/introduction-to-cpp.php)
C++ Programs (../cpp-programs/cpp-programs.php) Java Programs (../java-programs/java-programs-example)
Tutorialscity 2016
(https://www.facebook.com/tutorialscityindia/) () (https://plus.google.com/u/0/108642049011677927484)
TutorialsCity (../index.php)
Home (../index.php) Core Java (introduction-to-java.php) Collection (introduction-to-collection.php) JDBC (jdbc-in-java.php)
)
) )
HashMap (hashmap-in-collection.php)
TreeMap (treemap-in-collection.php)
LinkedHashMap (linkedhashmap-in-collection.php)
JDBC (jdbc-in-java.php)
LinkedHashMap In Java
LinkedHashMap
Java LinkedHashMap is same as Hash Map only difference is that it maintain an
insertion order. It means it the data in the same order in which they are inserted.
LinkedHashMap implements the Map interface and extends
HashMap class. A LinkedHashMap contains key - value pair
each key is associated with value. It can store one null key
and multiple null values.
LinkedHashMapExample
import java.util.*;
class LinkedHashMapExample {
public static void main(String args[]) { LinkedHashMap student = new LinkedHashMap(); student.put(1001, "Vinay");
student.put(1002, "Ankita"); student.put(1003, "Abhishek");
for (Map.Entry m : student.entrySet()) { System.out.println(m.getKey() + " " + m.getValue());
}
}
}
Output
1001 Vinay
1002 Ankita
1003 Abhishek
Our Tutorials Java Tutorials (introduction-to-java.php) Collection Tutorials (introduction-to-collection.php) JDBC Tutorials (jdbc-in-
java.php) C++ Tutorials (../cpp/introduction-to-cpp.php)
C++ Programs (../cpp-programs/cpp-programs.php) Java Programs (../java-programs/java-programs-example)
Tutorialscity 2016
(https://www.facebook.com/tutorialscityindia/) () (https://plus.google.com/u/0/108642049011677927484)
TutorialsCity (../index.php)
Home (../index.php) Core Java (introduction-to-java.php) Collection (introduction-to-collection.php) JDBC (jdbc-in-java.php)
)
) )
HashMap (hashmap-in-collection.php)
TreeMap (treemap-in-collection.php)
LinkedHashMap (linkedhashmap-in-collection.php)
JDBC (jdbc-in-java.php)
Tutorialscity 2016
(https://www.facebook.com/tutorialscityindia/) () (https://plus.google.com/u/0/108642049011677927484)
TutorialsCity (../index.php)
Home (../index.php) Core Java (introduction-to-java.php) Collection (introduction-to-collection.php) JDBC (jdbc-in-java.php)
)
) )
HashMap (hashmap-in-collection.php)
TreeMap (treemap-in-collection.php)
LinkedHashMap (linkedhashmap-in-collection.php)
JDBC (jdbc-in-java.php)
Our Tutorials Java Tutorials (introduction-to-java.php) Collection Tutorials (introduction-to-collection.php) JDBC Tutorials (jdbc-in-
java.php) C++ Tutorials (../cpp/introduction-to-cpp.php)
C++ Programs (../cpp-programs/cpp-programs.php) Java Programs (../java-programs/java-programs-example)
Tutorialscity 2016
(https://www.facebook.com/tutorialscityindia/) () (https://plus.google.com/u/0/108642049011677927484)
TutorialsCity (../index.php)
Home (../index.php) Core Java (introduction-to-java.php) Collection (introduction-to-collection.php) JDBC (jdbc-in-java.php)
)
) )
HashMap (hashmap-in-collection.php)
TreeMap (treemap-in-collection.php)
LinkedHashMap (linkedhashmap-in-collection.php)
JDBC (jdbc-in-java.php)
Performance Hash set is faster than Linked Hash set is slower than Tree Tree Hash set is slower
Linked Hash Set and Set but faster than Tree Hash Set than Linked Hash Set and
Tree Set Hash Set
Implementation Hash Set is implemented Linked Hash set is implemented by Tree set is implemented by
by HashMap Hash table which internally uses Tree Has Set
Link list
Null Values Has set can store null Linked Hash set can store null Tree Hash set cannot store
value value null value
ordering Hash do not maintain LinkList store the elements in the TreeHash set maintain the
insertion order same order in which they are sorted order
inserted
Tutorialscity 2016
(https://www.facebook.com/tutorialscityindia/) () (https://plus.google.com/u/0/108642049011677927484)
TutorialsCity (../index.php)
Home (../index.php) Core Java (introduction-to-java.php) Collection (introduction-to-collection.php) JDBC (jdbc-in-java.php)
Advantages-Of-OOPS (advantages-of-oops-in-java.php)
String (what-is-string-in-java.php)
Swing (swing-in-java.php)
Collection (introduction-to-collection.php)
JDBC (jdbc-in-java.php)
There are 5 steps required to connect java application to database given below:
5. Closing connection
In First step you need to load jdbc drivers this loading process known as Driver
registration. Class.forName() is used for loading drivers.
Syntax
HostName - is the name of the host where data base is located . If data base is on
your local system hostname is localhost
PortNo - Port number is required to make connection with database by default port
number is 1521. Username and Password - get connection method also requires
username and password of database.default username is root and password is
password.
After establishing connection with database we can interact with database through
JDBC statement. JDBC statement allows you to insert, select and delete data from
database.
After creating the statement object you can execute queries to the database. there are
three execute methods of statement in java given below:
a. boolean execute (String query):
Execute method used to perform all operation(insert,delete,update and select) it
returns a boolean value - True , False .
True-if it TRUE then it indicate result is Result Set . It means select operation is performed.
False -if it FALSE then it indicate result is int value that shows how many rows
affected by query. Operation can be insert, delete and update.
Our Tutorials Java Tutorials (introduction-to-java.php) Collection Tutorials (introduction-to-collection.php) JDBC Tutorials (jdbc-in-
java.php) C++ Tutorials (../cpp/introduction-to-cpp.php)
C++ Programs (../cpp-programs/cpp-programs.php) Java Programs (../java-programs/java-programs-example)
Tutorialscity 2016
(https://www.facebook.com/tutorialscityindia/) ()
(https://plus.google.com/u/0/108642049011677927484)
TutorialsCity (../index.php)
Home (../index.php) Core Java (introduction-to-java.php) Collection (introduction-to-collection.php) JDBC (jdbc-in-java.php)
Advantages-Of-OOPS (advantages-of-oops-in-java.php)
String (what-is-string-in-java.php)
Swing (swing-in-java.php)
Collection (introduction-to-collection.php)
JDBC (jdbc-in-java.php)
There are 5 steps required to connect java application and perform operation with
mysql database given below:
5. Closing connection
In First step you need to load jdbc drivers this loading process known as
Driver registration. com.mysql.jdbc.Driver class is required for mysql
database.
Syntax
Class.forName("com.mysql.jdbc.Driver");
2 Create a Database Connection
Syntax:
HostName - is the name of the host where data base is located .If data base is on
your local system hostname is localhost.
PortNo - Port number is required to make connection with database by default port number
is 1521. Username and Password - username and password are the database username
and password.default username is root and password is password.
After establishing connection with database we can interact with database through
JDBC statement. JDBC statement allows you to insert, select and delete data from
database
After creating the statement object you can execute queries to the database. There are
three execute methods of statement in java given below:
1. boolean execute (String query) - execute method used to perform all
operation(insert,delete,update and select).it returns a boolean value - True , False.
True - if it TRUE then it indicate result is Result Set . It means select operation is performed.
False - if it FALSE then it indicate result is int value that shows how many rows affected
by query . Operation can be insert,delete and update.
3. ResultSet executeQuery (String query) - executeQuery is used for select operation in Java.
ResultSet executeQuery method Returns a ResultSet object which contain complete
data of select query.
Our Tutorials Java Tutorials (introduction-to-java.php) Collection Tutorials (introduction-to-collection.php) JDBC Tutorials (jdbc-in-
java.php) C++ Tutorials (../cpp/introduction-to-cpp.php)
C++ Programs (../cpp-programs/cpp-programs.php) Java Programs (../java-programs/java-programs-example)
Tutorialscity 2016
(https://www.facebook.com/tutorialscityindia/) () (https://plus.google.com/u/0/108642049011677927484)
TutorialsCity (../index.php)
Home (../index.php) Core Java (introduction-to-java.php) Collection (introduction-to-collection.php) JDBC (jdbc-in-java.php)
Advantages-Of-OOPS (advantages-of-oops-in-java.php)
String (what-is-string-in-java.php)
Swing (swing-in-java.php)
Collection (introduction-to-collection.php)
JDBC (jdbc-in-java.php)
There are 5 steps required to connect java application and perform operation with
Oracle database given below:
5. Closing connection
In First step you need to load jdbc drivers this loading process known as
Driver registration. oracle.jdbc.driver.OracleDriver is required for Oracle
database.
Syntax
Class.forName("oracle.jdbc.driver.OracleDriver");
2 Create a Database Connection
Syntax:
HostName - is the name of the host where data base is located .If data base is on your
local system hostname is localhost
PortNo - Port number is required to make connection with database by default port number is 1521.
username and password - username and password are the database username and
password.default username is root and password is password
After establishing connection with database we can interact with database through
JDBC statement. JDBC statement allows you to insert, select and delete data from
database.
After creating the statement object you can execute queries to the database. There are
three execute methods of statement in java given below:
1. boolean execute (String query)
execute method used to perform all operation(insert,delete,update and select).it returns a boolean value - True ,
False.
True - if it TRUE then it indicate result is Result Set . It means select operation is performed.
False - if it FALSE then it indicate result is int value that shows how many rows affected by query . Operation can
be insert,delete and update.
Our Tutorials Java Tutorials (introduction-to-java.php) Collection Tutorials (introduction-to-collection.php) JDBC Tutorials (jdbc-in-
java.php) C++ Tutorials (../cpp/introduction-to-cpp.php)
C++ Programs (../cpp-programs/cpp-programs.php) Java Programs (../java-programs/java-programs-example)
Tutorialscity 2016
(https://www.facebook.com/tutorialscityindia/) ()
(https://plus.google.com/u/0/108642049011677927484)
TutorialsCity
Home
Core Java
Colection
JDBC C+
+
C++ Programs
Java Interview Programs
Basics of Java
Advantages-Of-OOPS
String
Exception Handling
Multithreading in Java
I/O In Java
Swing
Collection
JDBC
Introduction to JDBC
JDBC Connectivity Steps
MySql Connectivity with Java
Oracle Connectivity with Java
PreparedStatement In Java
Statement In Java
ResultSet In Java
Programs In Java
Interview Questions In Java
Prev
Next
Our Tutorials Java Tutorials Col ection Tutorials JDBC Tutorials C++ Tutorials
C++ Programs Java Programs
Tutorialscity 2016
TutorialsCity (../index.php)
Home (../index.php) Core Java (introduction-to-java.php) Collection (introduction-to-collection.php) JDBC (jdbc-in-java.php)
Advantages-Of-OOPS (advantages-of-oops-in-java.php)
String (what-is-string-in-java.php)
Swing (swing-in-java.php)
Collection (introduction-to-collection.php)
JDBC (jdbc-in-java.php)
After establishing connection with database we can interact with database through
JDBC statement. JDBC statement allows you to insert, select and delete data from
database.
1. Statement
2. PreparedStatement
3. CallableStatement
a. Statement
Statement is used for static queries it means when you do not wanna change your
query you can use simple statement.
It is suitable if you do not want run your query multiple times.
b. PreparedStatement
PreparedStatement is used for dynamic queries because it accepts input
parameter at run time. Prepared statement is useful when you want to
execute your query for multiple times.
Prepared statement is more ecient because it is pre-compiled.
c. CallableStatement
class MysqlExample {
public static void main(String args[]) { try { Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/test_db", "root", "1234");
// test_db is database name root is user name and 1234 is password
Statement stmt = con.createStatement();
while (rs.next())
System.out.println(rs.getInt(1) + " " + rs.getString(2) + " " + rs.getString(3)); con.close();
} catch (Exception e) { System.out.println(e);
}
}
Output
ankita btech
Kamal BCA
Rahul MCA
Karan BSC
class MysqlExample {
public static void main(String args[]) { try { Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/test_db", "root", "1234");
// test_db is database name root is user name and 1234 is password
Statement stmt = con.createStatement();
con.close();
} catch (Exception e) { System.out.println(e);
}
}
Output
No Of Rows effected 1
Execute Example
import java.sql.*;
class MysqlExample {
public static void main(String args[]) { try { Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/test_db", "root", "1234");
// test_db is database name root is user name and 1234 is password
Statement stmt = con.createStatement();
con.close();
} catch (Exception e) { System.out.println(e);
}
}
Output
Tutorialscity 2016
(https://www.facebook.com/tutorialscityindia/) () (https://plus.google.com/u/0/108642049011677927484)
TutorialsCity (../index.php)
Home (../index.php) Core Java (introduction-to-java.php) Collection (introduction-to-collection.php) JDBC (jdbc-in-java.php)
Advantages-Of-OOPS (advantages-of-oops-in-java.php)
String (what-is-string-in-java.php)
Swing (swing-in-java.php)
Collection (introduction-to-collection.php)
JDBC (jdbc-in-java.php)
ResultSet In Java
Reseultset
Resultset is used to read data from the database . Reseultset object point to first
row of the table after executing sql query.
Resultset can be used only with select command because delete, update and
insert does not returns data it returns only number of rows effected from
query.
class MysqlExample {
public static void main(String args[]) { try { Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/test_db", "root", "1234");
// test_db is database name root is user name and 1234 is password
Statement stmt = con.createStatement();
Output
Ankita BTECH
Kamal BSC
Our Tutorials Java Tutorials (introduction-to-java.php) Collection Tutorials (introduction-to-collection.php) JDBC Tutorials (jdbc-in-
java.php) C++ Tutorials (../cpp/introduction-to-cpp.php)
C++ Programs (../cpp-programs/cpp-programs.php) Java Programs (../java-programs/java-programs-example)
Tutorialscity 2016
(https://www.facebook.com/tutorialscityindia/) () (https://plus.google.com/u/0/108642049011677927484)
TutorialsCity (../index.php)
Home (../index.php) Core Java (introduction-to-java.php) Collection (introduction-to-collection.php) JDBC (jdbc-in-java.php)
Advantages-Of-OOPS (advantages-of-oops-in-java.php)
String (what-is-string-in-java.php)
Swing (swing-in-java.php)
Collection (introduction-to-collection.php)
JDBC (jdbc-in-java.php)
Tutorialscity 2016
(https://www.facebook.com/tutorialscityindia/) () (https://plus.google.com/u/0/108642049011677927484)
TutorialsCity (../index.php)
Home (../index.php) Core Java (../java/introduction-to-java.php) Collection (../java/introduction-to-collection.php) JDBC (../java/jdbc-in-java.php)
Output
Prev ()
TutorialsCity (../index.php)
Home (../index.php) Core Java (../java/introduction-to-java.php) Collection (../java/introduction-to-collection.php) JDBC (../java/jdbc-in-java.php)
public class CommandLineArgument { public static void main(String[] args) { String argument1 = args[0];
String argument2 = args[1];
int arguemnt3 = Integer.parseInt(args[3]); System.out.println("Student name : " + argument1 + " Course : "
+ argument2 + " Roll no : " + arguemnt3);
}
}
Output
Prev (hello-word-program.php) Next (arthematic-operation.php)
TutorialsCity (../index.php)
Home (../index.php) Core Java (../java/introduction-to-java.php) Collection (../java/introduction-to-collection.php) JDBC (../java/jdbc-in-java.php)
Output
10 + 20 = 30
10 * 20 = 200
10 / 20 = 0
10 % 20 = 10
TutorialsCity (../index.php)
Home (../index.php) Core Java (../java/introduction-to-java.php) Collection (../java/introduction-to-collection.php) JDBC (../java/jdbc-in-java.php)
Output
Output
TutorialsCity (../index.php)
Home (../index.php) Core Java (../java/introduction-to-java.php) Collection (../java/introduction-to-collection.php) JDBC (../java/jdbc-in-java.php)
class JavaPrimeExample {
public static void main(String args[]) {
int i, last = 0, ag = 0;
int value = 17;// it is the number to be checked
last = value / 2;
for (i = 2; i <= last; i++) {
if (value % i == 0) {
System.out.println(value+" is not a prime Number"); ag = 1;
break;
}
}
if (ag == 0)
System.out.println(value+" is a prime Number");
}
}
Output
'
17 is a prime Number
TutorialsCity (../index.php)
Home (../index.php) Core Java (../java/introduction-to-java.php) Collection (../java/introduction-to-collection.php) JDBC (../java/jdbc-in-java.php)
class JavaPalindromeExample {
public static void main(String args[]) {
int rem, sum = 0, temp;
int no = 161;// it is a value that need to be checked for palindrome temp = no;
while (no > 0) {
rem = no % 10; // getting remainder sum = (sum * 10) + rem;
no = no / 10;
}
if (temp == sum) // checking number with number reverse System.out.println(temp + " is a palindrome number "); else
System.out.println(temp + " is not palindrom number");
}
}
Output
public class
ReversenoExample { public
static void main(String[] args) {
int no = 12345; // original
no
int reversedno =
0; int reminder =
0; while (no > 0) {
reminder = no %
10;
reversedno = reversedno * 10 + reminder;
no = no / 10;
}
System.out.println("Reverse of no : " + reversedno); // Print the Reverse of no
Output
Reverse of no : 54321
int numbers[] = new int[] { 10, 20, 5, 1, 100 }; // define array of 5 numbers
// assign first element of an array
to largest and smallest
int min = numbers[0];
int max = numbers[0];
for (int i = 1; i < numbers.length; +i +) {
if (numbers[i] > max) max = numbers[i];
else if (numbers[i] < min) min = numbers[i];
}
System.out.println("max Number is : " + max); System.out.println("min Number is : " + min);
}
}
Output
Output
0
1
2
3
4
5
6
7
8
9
TutorialsCity (../index.php)
Home (../index.php) Core Java (../java/introduction-to-java.php) Collection (../java/introduction-to-collection.php) JDBC (../java/jdbc-in-java.php)
Output
import java.util.ArrayList;
import java.util.Collections;
public class ReverseArrayListExample { public static void main(String[] args) { ArrayList al = new ArrayList(); al.add("1");
al.add("2");
al.add("3");
al.add("4");
al.add("5");
System.out.println("Before Reverse : " + al); Collections.reverse(al); System.out.println("After Reverse : " + al);
}
}
Output
import java.util.Arrays;
public class ArrayMinMaxExample {
public static void main(String[] args) {
int values[] = new int[] { 8, 2, 7, 1, 4, 9, 5 };
// Sort the array using sort method Arrays.sort(values);
// minimum value at first position System.out.println("Min Vlaues is :" + values[0]);
// maximum value at last position
System.out.println("Min Vlaues is :" + values[values.length - 1]);
}
}
Output
}
public static void main(String[] args) {
int numbers[] = new int[] { 10, 5, 20, 1, 100 }; // dene array of 5 numbers
System.out.println("Array Before deleteion:");
for (int i = 0; i < numbers.length; i++)
{ System.out.println(numbers[i]);
}
RemoveElementFromArray obj = new RemoveElementFromArray();
obj.delete(numbers, 3); // call the delete method
}
}
Output
int numbers[] = new int[] { 10, 5, 20, 1, 100 System.out.println("Array Before deleteion:"); for (int i = 0; i };
< numbers.length; i++)
// define array of { System.out.pr
5 numbers
}
RemoveElementFromArray obj = new RemoveElementFromArray(); obj.delete(numbers, 3); // call the delete meth
}
}
Output
Array Before deleteion: 10
5
20
1
100
import java.util.Arrays;
public class InsertElementInArray {
void insert(int array1[], int value, int pos) {
int temp;
int size = array1.length;
int array2[] = new int[size + 1];
System.arraycopy(array1, 0, array2, 0, pos);
// Copy values from start to pos from array1 to array2
for (int i = 0; i < pos; i++)
{ array2[i] = array1[i];
}
}
public static void main(String[] args) {
int numbers[] = new int[] { 10, 5, 20, 1, 100 }; // dene array of 5 numbers
System.out.println("Array Before Insertion:");
for (int i = 0; i < numbers.length; i++)
{ System.out.println(numbers[i]);
}
InsertElementInArray obj = new InsertElementInArray(); obj.insert(numbers, 12, 3); // call the insert method
}
}
Output
}
Output
20
100
20
12
100
import java.text.SimpleDateFormat;
import java.util.Date;
public class DisplayTimeExample{
public static void main(String[] args){ Date date = new Date(); System.out.println(date.toString());
}
}
Output
import java.text.SimpleDateFormat;
import java.util.Date;
public class DisplayTimeExample {
public static void main(String[]
args) { Date date = new Date();
String TimeFormat = "HH:mm:ss a";
String DateFormat = "MM.dd.yyyy";
String DateTimeFormat = "MM.dd.yyyy hh:mm:ss a ";
String DayDateTimeFormat = "E MM.dd.yyyy hh:mm:ss a ";
SimpleDateFormat ft;
ft = new
SimpleDateFormat(TimeFormat);
System.out.println(ft.format(date));
ft = new
SimpleDateFormat(DateFormat);
System.out.println(ft.format(date));
ft = new SimpleDateFormat(DateTimeFormat);
System.out.println(ft.format(date));
ft = new SimpleDateFormat(DayDateTimeFormat);
System.out.println(ft.format(date));
}
Output
13:32:56 PM
08.25.2016
08.25.2016 01:32:56 PM
Thu 08.25.2016 01:32:56 PM
TutorialsCity (../index.php)
Home (../index.php) Core Java (../java/introduction-to-java.php) Collection (../java/introduction-to-collection.php) JDBC (../java/jdbc-in-java.php)
public class CompareStringExample { public static void main(String args[]) { String source = "Java Tutorials";
String dest = "java tutorials"; String destCopy = dest;
System.out.println(source.compareTo(dest)); System.out.println(source.compareToIgnoreCase(dest)); System.out.println(source.equals(dest)); System.out.prin
System.out.println(dest == destCopy);
}
}
Output
-32
0
false true false true
TutorialsCity (../index.php)
Home (../index.php) Core Java (../java/introduction-to-java.php) Collection (../java/introduction-to-collection.php) JDBC (../java/jdbc-in-java.php)
Output
Java
Trograms
Jeva
Programs
Jeve
Progrems
Java
Tutorials
Prev (string-comparison-program.php) Next (reverse-string-Using-reverse-method.php)
TutorialsCity (../index.php)
Home (../index.php) Core Java (../java/introduction-to-java.php) Collection (../java/introduction-to-collection.php) JDBC (../java/jdbc-in-java.php)
Output
at " + lastindex);
Output
Output
Java String split using java split
-------------------------
Java String
TutorialsCity (../index.php)
Home (../index.php) Core Java (../java/introduction-to-java.php) Collection (../java/introduction-to-collection.php) JDBC (../java/jdbc-in-java.php)
}
}
Output
Remove Remove
first Remove
first last
character- tring in java
Remove Mid
word- word-
in java String in
word- String java
TutorialsCity (../index.php)
Home (../index.php) Core Java (../java/introduction-to-java.php) Collection (../java/introduction-to-collection.php) JDBC (../java/jdbc-in-java.php)
import java.io.*;
class FileInputStreamExample{
public static void main(String args[]){
try{
FileInputStream fin=new FileInputStream("file.txt");
int i=0; while((i=fin.read())!=-1){ System.out.println((char)i);
}
fin.close(); System.out.println("\nDone..");
}catch(Exception e){System.out.println(e);}
}
}
Output
L
i
n
t
a
i
n
d
TutorialsCity (../index.php)
Home (../index.php) Core Java (../java/introduction-to-java.php) Collection (../java/introduction-to-collection.php) JDBC (../java/jdbc-in-java.php)
import java.io.*;
class FileReadLineByLineExample { public static void main(String args[]) { try {
FileReader fin = new FileReader("file.txt"); BufferedReader br = new BufferedReader(fin); String s = "";
while ((s = br.readLine()) != null) { System.out.println(s);
}
fin.close(); System.out.println("\nDone..");
} catch (Exception e) { System.out.println(e);
}
}
}
Output
Output
TutorialsCity (../index.php)
Home (../index.php) Core Java (../java/introduction-to-java.php) Collection (../java/introduction-to-collection.php) JDBC (../java/jdbc-in-java.php)
Output
TutorialsCity (../index.php)
Home (../index.php) Core Java (../java/introduction-to-java.php) Collection (../java/introduction-to-collection.php) JDBC (../java/jdbc-in-java.php)
import java.io.*;
class BinaryToDecimal { BinaryToDecimal(int value) { int rem;
int decimal_value = 0;
int i = 0;
while (value > 0) { rem = value % 10;
decimal_value = (int) (decimal_value + rem * Math.pow(2, i)); i++;
value = value / 10;
}
System.out.println(value + " Decimal vale is " + decimal_value);
}
public static void main(String args[]) { BinaryToDecimal obj = new BinaryToDecimal(1000000);
}
}
Output
import java.io.*;
class BinaryToDecimal { BinaryToDecimal(int value) { int rem;
int decimal_value = 0;
int i = 0;
Output
1000000 Decimal vale is 64
TutorialsCity (../index.php)
Home (../index.php) Core Java (../java/introduction-to-java.php) Collection (../java/introduction-to-collection.php) JDBC (../java/jdbc-in-java.php)
import java.util.*;
import java.util.Arrays;
class ArrayToCollectionConversion {
public static void main(String args[]) {
String a[] = { "rahul", "abhi", "rajan", "anu", "ankita" }; List al = Arrays.asList(a);
for (int i = 0; i < al.size(); i++) { System.out.println(al.get(i).toString());
}
}
}
Output
import java.util.*;
import java.util.Arrays;
class CollectionToArrayConversion { public static void main(String args[]) { List al = new ArrayList();
al.add("rahul");
al.add("abhi");
al.add("rajan");
al.add("anu");
al.add("ankita");
String s[] = al.toArray(new String[0]); for (int i = 0; i < s.length; i++) { System.out.println(s[i]);
}
}
}
Output
Java String Start With & ends with and conatin Program
Java String Start With & ends with and conatin Program
Java String Start With & ends with and conatin Program
Output
true false false
-------
false true false
-------
true false true
TutorialsCity (../index.php)
Home (../index.php) Core Java (../java/introduction-to-java.php) Collection (../java/introduction-to-collection.php) JDBC (../java/jdbc-in-java.php)
Output
TutorialsCity (../index.php)
Home (../index.php) Core Java (../java/introduction-to-java.php) Collection (../java/introduction-to-collection.php) JDBC (../java/jdbc-in-java.php)
Output
TutorialsCity (../index.php)
Home (../index.php) Core Java (../java/introduction-to-java.php) Collection (../java/introduction-to-collection.php) JDBC (../java/jdbc-in-java.php)
Output
TutorialsCity (../index.php)
Home (../index.php) Core Java (../java/introduction-to-java.php) Collection (../java/introduction-to-collection.php) JDBC (../java/jdbc-in-java.php)
* b));
{
* b) + (c * c));
args[]) {
Output
100
500
1400
TutorialsCity (../index.php)
Home (../index.php) Core Java (../java/introduction-to-java.php) Collection (../java/introduction-to-collection.php) JDBC (../java/jdbc-in-java.php)
Output
TutorialsCity (../index.php)
Home (../index.php) Core Java (../java/introduction-to-java.php) Collection (../java/introduction-to-collection.php) JDBC (../java/jdbc-in-java.php)
Output
TutorialsCity (../index.php)
Home (../index.php) Core Java (../java/introduction-to-java.php) Collection (../java/introduction-to-collection.php) JDBC (../java/jdbc-in-java.php)
Output
TutorialsCity (../index.php)
Home (../index.php) Core Java (../java/introduction-to-java.php) Collection (../java/introduction-to-collection.php) JDBC (../java/jdbc-in-java.php)
Output
TutorialsCity (../index.php)
Home (../index.php) Core Java (../java/introduction-to-java.php) Collection (../java/introduction-to-collection.php) JDBC (../java/jdbc-in-java.php)
Output
TutorialsCity (../index.php)
Home (../index.php) Core Java (../java/introduction-to-java.php) Collection (../java/introduction-to-collection.php) JDBC (../java/jdbc-in-java.php)
Output
TutorialsCity (../index.php)
Home (../index.php) Core Java (../java/introduction-to-java.php) Collection (../java/introduction-to-collection.php) JDBC (../java/jdbc-in-java.php)
Output
TutorialsCity (../index.php)
Home (../index.php) Core Java (../java/introduction-to-java.php) Collection (../java/introduction-to-collection.php) JDBC (../java/jdbc-in-java.php)
Output
TutorialsCity (../index.php)
Home (../index.php) Core Java (../java/introduction-to-java.php) Collection (../java/introduction-to-collection.php) JDBC (../java/jdbc-in-java.php)
Output
TutorialsCity (../index.php)
Home (../index.php) Core Java (../java/introduction-to-java.php) Collection (../java/introduction-to-collection.php) JDBC (../java/jdbc-in-java.php)
Output
TutorialsCity (../index.php)
Home (../index.php) Core Java (../java/introduction-to-java.php) Collection (../java/introduction-to-collection.php) JDBC (../java/jdbc-in-java.php)
Output
TutorialsCity (../index.php)
Home (../index.php) Core Java (../java/introduction-to-java.php) Collection (../java/introduction-to-collection.php) JDBC (../java/jdbc-in-java.php)
import java.util.Scanner;
public class
BubbleSortExample { public
static void main(String[] args) {
int n;
int a[] = new int[100];
Scanner sc = new Scanner(System.in);
System.out.println("Enter the total no of
elements"); n = sc.nextInt();
System.out.println("Enter array values");
for (int i = 0; i< n;
i++) a[i] =
sc.nextInt();
for (int i = 0; i < (n - 1); i++) {
for (int j = 0; j< n- i - 1; j++) {
if (a[j] > a[j + 1]) /* For decreasing order use < */
{
int temp =
a[j]; a[j] =
a[j + 1]; a[j
+ 1] =
temp;
}
}
System.out.println("Sorted list in ascending order:");
for (int i = 0; i < n; i++)
System.out.println(a[i]);
}
}
Output
55
21
Sorted list in ascending
order: 2
3
11
21
55
import java.util.Scanner;
public class SelectionSortExample {
public static void main(String[]
args) { int n;
int a[] = new int[100];
Scanner sc = new Scanner(System.in);
System.out.println("Enter the total no of elements");
n = sc.nextInt();
System.out.println("Enter a values");
}
System.out.println("Sorted list in ascending order:");
Output
7
Sorted list in ascending order:
3
4
}
Output
10
10
import java.util.Arrays;
public class SortArrayExample {
void sort(int a[]) {
int temp;
for (int i = 0; i < a.length - 1; i++) {
for (int j = i + 1; j < a.length; j++) {
if (a[i] > a[j]) {
temp = a[i];
a[i] = a[j];
a[j] = temp;
}
}
}
Output
Un Sorted Array: 10
5
20
1
100
Sorted Array: 1
5
10
20
100
Output
Un Sorted Array: 10
5
20
1
100
Sorted Array: 1
5
10
20
100
TutorialsCity (../index.php)
Home (../index.php) Core Java (../java/introduction-to-java.php) Collection (../java/introduction-to-collection.php) JDBC (../java/jdbc-in-java.php)
import java.io.*;
class LinearSearchExample {
public static void main(String args[]) {
int a[] = { 10, 20, 30, 40, 50, 60, 70 };
int searchItem = 40;
int index = 0, ag = 0;
for (int i = 0; i < a.length; i++) {
if (a[i] == searchItem) { ag = 1;
index = i;
break;
}
}
if (ag == 1)
System.out.println(searchItem + " Element found at " + index);
else
System.out.println(searchItem + " Element not found");
}
}
Output
40 Element found at 3
TutorialsCity (../index.php)
Home (../index.php) Core Java (../java/introduction-to-java.php) Collection (../java/introduction-to-collection.php) JDBC (../java/jdbc-in-java.php)
import java.io.*;
class BinarySearchExample {
public static void main(String args[]) {
int a[] = { 10, 20, 30, 40, 50, 60, 70 };
int searchItem = 30;
int index = 0, ag = 0, first,
last, mid; first = 0;
last = a.length -
1; mid = (first +
last) / 2; while
(first <= last) {
if (searchItem < a[mid]) {
last = mid - 1;
} else if (searchItem >
a[mid]) { first = mid +
1;
} else {
System.out.println(searchItem + " Found at " + (mid + 1));
break;
}
mid = (first + last) / 2;
}
if (first > last) {
System.out.println(searchItem + " Not Found");
}
Output
30 Found at 3
Next ()