JAVA unit1
JAVA unit1
Unit – I
Introduction: Java Essentials, JVM, Java Features,
Creation and Execution of Programs, Data Types,
TypeConversion, Casting, Conditional Statements,
Loops, Branching Mechanism, Classes, Objects,
ClassDeclaration, Creating Objects, Method
Declaration and Invocation, Method Overloading,
Constructors–Parameterized Constructors,
Constructor Overloading, Cleaning-up unused
Objects, Class Variables &Methods-static Keyword,
this Keyword, One-Dimensional Arrays, Two-
Dimensional Arrays, Command-LineArguments,
Inner Class.
Inheritance: Introduction, Types of Inheritance,
extends Keyword, Examples, Method Overriding,
super, finalKeywords, Abstract classes, Interfaces,
Abstract Classes Verses Interfaces.
Unit – II
Packages–Creating and Using Packages, Access
Protection, Wrapper Classes, String Class,
StringBuffer Class.
Exception: Introduction, Types, Exception Handling
Techniques, User-Defined Exception.
Multithreading: Introduction, Main Thread, Creation
of New Threads – By Inheriting the Thread Class or
Implementing the Runnable Interface, Thread
Lifecycle, Thread Priority, Synchronization.
Input/Output: Introduction, java.io Package, File
Class, FileInputStream Class, FileOutputStream
Class,
Scanner Class, BufferedInputStream Class,
BufferedOutputStream Class, RandomAccessFile
Class.
Unit – III
Applets: Introduction, Example, Life Cycle, Applet
Class, Common Methods Used in Displaying the
Output.
Event Handling: Introduction, Types of Events,
Example. AWT: Introduction, Components,
Containers, Button,
Label, Checkbox, Radio Buttons, Container Class,
Layouts. Swing: Introduction, Differences between
Swing
and AWT, Jframe, Japplet, Jpanel, Components in
Swings, Layout Managers, Jtable, Dialog Box.
Database Handling Using JDBC: Introduction,
Types of JDBC Drivers, Load the Driver, Establish
Connection,
Create Statement, Execute Query, IterateResultset,
Scrollable Resultset, Developing a JDBS
Application.
INTRODUCTION TO JAVA:
Java is an object-oriented programming
language with its runtime environment. It is a
combination of features of C and C++ with some
essential additional concepts. Java is well suited for
both standalone and web application development
and is designed to provide solutions to most of the
problems faced by users of the internet era.
What is Java?
publicclassMyFirstJavaProgram{
publicstaticvoid main(String[]args){
System.out.println("Hello World");// prints Hello
World
}
}
Let's look at how to save the file, compile, and run
the program. Please follow the subsequent steps −
Open notepad and add the code as above.
your program.
You will be able to see ' Hello World ' printed
on the window.
Output
C:\>javac MyFirstJavaProgram.java
C:\> java MyFirstJavaProgram
Hello World
Basic Syntax
About Java programs, it is very important to keep in
mind the following points.
Case Sensitivity − Java is case sensitive, which
Byte 0 1 byte
Short 0 2 byte
Int 0 4 byte
Long 0L 8 byte
Example:
classTest
{
publicstaticvoidmain(String[] args)
{
inti = 100;
//automatic type conversion
longl = i;
//automatic type conversion
floatf = l;
System.out.println("Int value "+i);
System.out.println("Long value "+l);
System.out.println("Float value "+f);
}
}
Output:
Int value 100
Long value 100
Float value 100.0
Narrowing or Explicit Conversion
If we want to assign a value of larger data type to a
smaller data type we perform explicit type casting or
narrowing.
This is useful for incompatible data types where
//d%256
b = (byte) d;
System.out.println("d = "+ d + " b= "+
b);
}
}
Output:
Conversion of int to byte.
i = 257 b = 1
Type Casting
1 packageClassThreeControlFlowStatements;
2
3 publicclassIfElseStatement{
4
5 publicstaticvoidmain(String[]args){
6
7 intnum=100;
8
9 if(num>100){
System.out.println("Value is greater than
10 100");
11 }else{
12 System.out.println("Value is less than
13 100");
14 }
15
16 }
17
}
if-else-if statement:
if(condition_1){
/*if condition_1 is true execute this*/
statement(s);
}
Else if(condition_2){
/* execute this if condition_1 is not met and
* condition_2 is met
*/
statement(s);
}
Else if(condition_3){
/* execute this if condition_1 & condition_2 are
* not met and condition_3 is met
*/
statement(s);
}
.
.
.
else{
/* if none of the condition is true
* then these statements gets executed
*/
statement(s);
}
1 packageClassThreeControlFlowStatements;
2
3 publicclassIfElseIfStatement{
4
5 publicstaticvoidmain(String[]args){
6
7 intmarks=76;
8 chargrade;
9
10 if(marks>=80){
11 grade='A';
12 }elseif(marks>=70){
13 grade='B';
14 }elseif(marks>=60){
15 grade='C';
16 }elseif(marks>=50){
17 grade='D';
18 }else{
19 grade='F';
20 }
21 System.out.println("Grade = "+grade);
22
23 }
24
25 }
Switch Case:
The switch statement in Java is a multi branch
statement. We use this in Java when we have
multiple options to select. It executes particular
option based on the value of an expression.
Switch works with the byte, short, char, and int
primitive data types. It also works with enumerated
types, the String class, and a few special classes that
wrap certain primitive types such as Character, Byte,
Short, and Integer.
SYNTAX
switch(expression){
1 casevalueOne:
2 //statement(s
3 break;
4 casevalueTwo:
5 //statement(s
6 break;
7:
8:
9:
10 default://optional
11 //statement(s) //This code will
12 be executed if all cases are not
13 matched
}
Sample Program:
1 packageClassThreeControlFlowStatements;
2
3 publicclassSwitchCaseProgram{
4
5 publicstaticvoidmain(String[]args){
6 /*The java switch statement is fall-through.
7 It means it executes all statement after first
8 match if break statement is not used with
switch cases.*/
9
intnum=200;
10
switch(num){
11
12
case100:
13
System.out.println("Value of Case 1 is
14 "+num);
15 case200:
16 System.out.println("Value of Case 2 is
17 "+num);
18 default:
System.out.println("Value of default is
"+num);
19
20 }
21
22 }
}
Switch Case with break statement:
packageClassThreeControlFlowStatements;
1
2 public class
3 SwitchCaseProgramWithBreak{
4
5 public static void main(String[]args){
6
7 int num=200;
8 switch(num){
9
10 case 100:
11 System.out.println("Value of Case 1 is
12 "+num);
13 break;
14 case 200:
15 System.out.println("Value of Case 2 is
"+num);
16
break;
17
// In this only case 2 will be executed and
18 rest of the cases will be ignored.
19 default:
20 System.out.println("Value of default is
21 "+num);
22
23 }
24
}
}
For Loop In Java
The for statement in Java allows us to repeatedly
loops until a particular condition is satisfied. Check
this post to learn enhanced for loop (for each)
Syntax:
For(initialization;termination;inc
1 rement){
2 //statement(s)
3}
Sample Program:
1 packageClassThreeControlFlowSt
2 atements;
3
4 publicclassSimpleForLoop{
5
6 publicstaticvoidmain(String[]args)
{
7
8
/*
9
* inti = 1; //Initialization
10
* i<=10; // Condition (Boolean
11 expression)
12 * i++ // Decrement operation
13 */
14 for(inti=1;i<=10;i++){
15
16 System.out.println("Value of i is
17 "+i);
18
}
19
}
20
}
While Loop In Java
Last Updated on June 8, 2018 by Rajkumar Leave a
Comment
In the last tutorial, we learnt for loop and enhanced
for loop and in this tutorial we will discuss while
loop.
1 packageClassThreeControlFlowStatements;
2
3 publicclassWhileLoop{
4
5 publicstaticvoidmain(String[]args){
6 inti=1;
7 while(i<=10){
8 System.out.println("Value of i is
9 "+i);
10 i++;
11 }
12 }
13
Do While Loop In Java
The do-while is similar to the while loop. In do-
while loop, the condition is evaluated after the
execution of statements with in the do block at least
once.
Syntax:
1 do
2{
3 //statement(s);
4 }while(condition);
Sample Program:
1 packageClassThreeControlFlowStatements;
2
3 publicclassDoWhileLoop{
4
5 publicstaticvoidmain(String[]args){
6 inti=10;
7 do{
8 System.out.println(i);
9 i--;
10 }
11 while(i>1);
12 }
13
14 }
Continue Statement
The Continue Statement in Java is used to continue
loop. It is widely used inside loops. Whenever the
continue statement is encountered inside a loop,
control immediately jumps to the beginning of the
loop for next iteration by skipping the execution of
statements inside the body of loop for the current
iteration.
Syntax:
continue;
Sample Program:
1 packageClassThreeControlFlowStatements;
2
3 public class ContinueStatement{
4
5 public static void main(String[] args){
6
7 for(int i=1;i<=10;i++)
8{
9 /* I have mentioned continue statement
10 inside if condition where i is equal to 4
11 * if i value is equal to 4 then the control
goes to continue statement and
12
* the control jumps at the begining of for
13 loop for next iteration without executing
14 * print statement.
15 * So, the output "Value of i is 4" wont
16 display in the console. */
if(i==4)
17
{
18
continue;
19
}
20
21
System.out.println("Value of i is "+i);
22
23
}
24
25
}
26
}
Break Statement In Java
The Break statement in Java is used to break a loop
statement or switch statement. The Break statement
breaks the current flow at a specified condition.
Note: In case of inner loop, it breaks just the inner
loop.
Syntax:
break;
Break Statement Sample Program:
1 packageClassThreeControlFlowStatements;
2
3 publicclassBreakStatement{
4
5 publicstaticvoidmain(String[]args){
6
7 for(inti=1;i<=10;i++)
8{
9 if(i==4)
10 {
11 break;
12 }
13
14 System.out.println("Value of i is "+i);
15
16 }
17
18 }
19
20 }
Break Statement within Switch Case:
Refer Switch Case Statement.
Break Statement with inner loop:
1 packageClassThreeControlFlowStatements;
2
3 publicclassBreakStatementInnerLoop{
4
5 publicstaticvoidmain(String[]args){
6
7 for(intx=1;x<=4;x++)
8{
9 for(inty=1;y<=4;y++){
10
11 if(x==2&&y==2)
{
12
System.out.println("Value of x is "+x+"
13
and Value of y is "+y);
14
break;
15
}
16
17
System.out.print(x);
18
System.out.println(y);
19
20
}
21
22
}
23
24
}
25
26
}
Classes and Objects.
Object − Objects have states and behaviors.
void barking(){
}
void hungry(){
}
void sleeping(){
}
}
A class can contain any of the following variable
types.
Local variables − Variables defined inside
methods, constructors or blocks are called local
variables. The variable will be declared and
initialized within the method and the variable
will be destroyed when the method has
completed.
Instance variables − Instance variables are
variables within a class but outside any method.
These variables are initialized when the class is
instantiated. Instance variables can be accessed
from inside any method, constructor or blocks
of that particular class.
Class variables − Class variables are variables
ult −
Output
Passed Name is :tommy
Methods in Java
A method is a collection of statements that perform
some specific task and return the result to the caller.
A method can perform some specific task without
returning anything. Methods allow us to reuse the
code without retyping the code. In Java, every
method must be part of some class which is different
from languages like C, C++, and Python.
Methods are time savers and help us to reuse the
code without retyping the code.
Method Declaration
In general, method declarations has six components :
Modifier-: Defines access type of the method i.e.
application.
protected: accessible within the class in which it
Throws an exception
return sum;
}
classGFG {
publicstaticvoidmain (String[] args) {
classTest
{
publicstaticinti = 0;
// constructor of class which counts
//the number of the objects of the class.
Test()
{
i++;
}
// static method is used to access static
members of the class
// and for getting total no of objects
// of the same class created so far
publicstaticintget()
{
// statements to be executed....
returni;
}
// Instance method calling object directly
// that is created inside another class
'GFG'.
// Can also be called by object directly
created in the same class
// and from another method defined in
the same class
// and return integer value as return type
is int.
publicintm1()
{
System.out.println("Inside the method
m1 by object of GFG class");
System.out.println("In method m2
came from method m1");
}
}
classGFG
{
publicstaticvoidmain(String[] args)
{
// Creating an instance of the class
Test obj = newTest();
System.out.print("No of instances
created till now : ");
System.out.println(no_of_objects);
}
}
Output :
Inside the method m1 by object of GFG class
In method m2 came from method m1
Control returned after method m1 :1
No of instances created till now : 1
33
Constructors in Java
Constructor is a block of code that initializes the
newly created object. A constructor resembles an
instance method in java but it’s not a method as it
doesn’t have a return type. In short constructor and
method are different(More on this at the end of this
guide). People often refer constructor as special type
of method in Java.
Constructor has same name as the class and looks
like this in a java code.
Public class MyClass{
//This is the constructor
MyClass(){
}
..
}
Note that the constructor name matches with the
class name and it doesn’t have a return type.
How does a constructor work
To understand the working of constructor, lets take
an example. lets say we have a class MyClass.
When we create the object of MyClass like this:
MyClassobj=newMyClass()
The new keyword here creates the object of
class MyClass and invokes the constructor to
initialize this newly created object.
You may get a little lost here as I have not shown
you any initialization example, lets have a look at
the code below:
A simple constructor program in java
Here we have created an object obj of
class Hello and then we displayed the instance
variable nameof the object. As you can see that the
output is BeginnersBook.com which is what we
have passed to the name during initialization in
constructor. This shows that when we created the
object obj the constructor got invoked. In this
example we have used this keyword, which refers
to the current object, object obj in this example. We
will cover this keyword in detail in the next tutorial.
Public class Hello{
String name;
//Constructor
Hello(){
this.name ="VBDC”;
}
Public static void main(String[]args){
Hello obj=new Hello();
System.out.println(obj.name);
}
}
Output:VBDC
Types of Constructors
There are three types of constructors: Default, No-
arg constructor and Parameterized.
Default constructor
If you do not implement any constructor in your
class, Java compiler inserts a default constructor into
your code on your behalf. This constructor is known
as default constructor. You would not find it in your
source code(the java file) as it would be inserted into
the code during compilation and exists in .class file.
This process is shown in the diagram below:
If you implement any constructor then you no longer
receive a default constructor from Java compiler.
no-arg constructor:
Constructor with no arguments is known as no-arg
constructor. The signature is same as default
constructor, however body can have any code unlike
default constructor where the body of the constructor
is empty.
Although you may see some people claim that that
default and no-arg constructor is same but in fact
they are not, even if you write public Demo() { } in
your class Demo it cannot be called default
constructor since you have written the code of it.
Example: no-arg constructor
Class Demo
{
Public Demo()
{
System.out.println("This is a no argument
constructor");
}
publicstaticvoid main(Stringargs[]){
newDemo();
}
}
Output:
This is a no argument constructor
Parameterized constructor
Constructor with arguments(or you can say
parameters) is known as Parameterized constructor.
Example: parameterized constructor
In this example we have a parameterized constructor
with two parameters id and name. While creating the
objects obj1 and obj2 I have passed two arguments
so that this constructor gets invoked after creation of
obj1 and obj2.
Public class Employee{
Int empId;
String empName;
//parameterized constructor with two parameters
Employee(int id,String name){
this.empId= id;
this.empName= name;
}
void info(){
System.out.println("Id: "+empId+" Name:
"+empName);
}
publicstaticvoid main(Stringargs[]){
Employee obj1
=newEmployee(10245,"Chaitanya");
Employee obj2
=newEmployee(92232,"Negan");
obj1.info();
obj2.info();
}
}
Output:
Id:10245Name:Chaitanya
Id:92232Name:Negan
Example2: parameterized constructor
In this example, we have two constructors, a default
constructor and a parameterized constructor. When
we do not pass any parameter while creating the
object using new keyword then default constructor is
invoked, however when you pass a parameter then
parameterized constructor that matches with the
passed parameters list gets invoked.
classExample2
{
privateintvar;
//default constructor
publicExample2()
{
this.var=10;
}
//parameterized constructor
publicExample2(intnum)
{
this.var= num;
}
publicintgetValue()
{
returnvar;
}
publicstaticvoid main(Stringargs[])
{
Example2obj=newExample2();
Example2 obj2 =newExample2(100);
System.out.println("var is: "+obj.getValue());
System.out.println("var is: "+obj2.getValue());
}
}
Output:
varis:10
varis:100
What if you implement only parameterized
constructor in class
classExample3
{
privateintvar;
publicExample3(intnum)
{
var=num;
}
publicintgetValue()
{
returnvar;
}
publicstaticvoid main(Stringargs[])
{
Example3myobj=newExample3();
System.out.println("value of var is:
"+myobj.getValue());
}
}
Output: It will throw a compilation error. The
reason is, the statement Example3 myobj = new
Example3() is invoking a default constructor which
we don’t have in our program. when you don’t
implement any constructor in your class, compiler
inserts the default constructor into your code,
however when you implement any constructor (in
above example I have implemented parameterized
constructor with int parameter), then you don’t
receive the default constructor by compiler into your
code.
If we remove the parameterized constructor from the
above code then the program would run fine,
because then compiler would insert the default
constructor into your code.
Constructor Chaining
When A constructor calls another constructor of
same class then this is called constructor chaining.
Read more about it here.
Super()
Whenever a child class constructor gets invoked it
implicitly invokes the constructor of parent class.
You can also say that the compiler inserts
a super(); statement at the beginning of child class
constructor.
classMyParentClass{
MyParentClass(){
System.out.println("MyParentClass
Constructor");
}
}
classMyChildClassextendsMyParentClass{
MyChildClass(){
System.out.println("MyChildClass
Constructor");
}
publicstaticvoid main(Stringargs[]){
newMyChildClass();
}
}
Output:
MyParentClassConstructor
MyChildClassConstructor
Read more about super keyword here.
Constructor Overloading
Constructor overloading is a concept of having more
than one constructor with different parameters list, in
such a way so that each constructor performs a
different task.