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

JAVA unit1

The document is a comprehensive guide on Java programming, covering essential topics such as Java basics, object-oriented principles, data types, inheritance, exception handling, multithreading, and GUI development. It explains the Java Virtual Machine (JVM), the differences between JDK, JRE, and JVM, and provides instructions for setting up a Java programming environment. Additionally, it includes practical examples and details on Java syntax, data types, and the execution of a simple Java program.

Uploaded by

sirisha
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
12 views

JAVA unit1

The document is a comprehensive guide on Java programming, covering essential topics such as Java basics, object-oriented principles, data types, inheritance, exception handling, multithreading, and GUI development. It explains the Java Virtual Machine (JVM), the differences between JDK, JRE, and JVM, and provides instructions for setting up a Java programming environment. Additionally, it includes practical examples and details on Java syntax, data types, and the execution of a simple Java program.

Uploaded by

sirisha
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 92

DSC–3E Programming in Java BS505

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.

Text Sachin Malhotra, SaurabhChoudhary,


Programming in Java (2e)

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?

 Java is an object-oriented programming language


developed by Sun Microsystems, and it was
released in 1995.
 James Gosling initially developed Java in Sun
Microsystems (which was later merged with Oracle
Corporation).
 Java is a set of features of C and C++. It has
obtained its format from C, and OOP features from
C++.
 Java programs are platform independent which
means they can be run on any operating system with
any processor as long as the Java interpreter is
available on that system.
 Java code that runs on one platform does not need
to be recompiled to run on another platform; it's
called write once, run anywhere(WORA).
 Java Virtual Machine (JVM) executes Java code,
but it has been written in platform-specific
languages such as C/C++/ASM, etc. JVM is not
written in Java and hence cannot be platform
independent, and Java interpreter is a part of JVM.

Features of Java
 Object Oriented − In Java, everything is an

Object. Java can be easily extended since it is


based on the Object model.
 Platform Independent − Unlike many other

programming languages including C and C++,


when Java is compiled, it is not compiled into
platform specific machine, rather into platform
independent byte code. This byte code is
distributed over the web and interpreted by the
Virtual Machine (JVM) on whichever platform
it is being run on.
 Simple − Java is designed to be easy to learn. If
you understand the basic concept of OOP Java,
it would be easy to master.
 Secure − With Java's secure feature it enables to
develop virus-free, tamper-free systems.
Authentication techniques are based on public-
key encryption.
 Architecture-neutral − Java compiler
generates an architecture-neutral object file
format, which makes the compiled code
executable on many processors, with the
presence of Java runtime system.
 Portable − Being architecture-neutral and
having no implementation dependent aspects of
the specification makes Java portable. Compiler
in Java is written in ANSI C with a clean
portability boundary, which is a POSIX subset.
 Robust − Java makes an effort to eliminate
error prone situations by emphasizing mainly on
compile time error checking and runtime
checking.
 Multithreaded − With Java's multithreaded
feature it is possible to write programs that can
perform many tasks simultaneously. This design
feature allows the developers to construct
interactive applications that can run smoothly.
 Interpreted − Java byte code is translated on

the fly to native machine instructions and is not


stored anywhere. The development process is
more rapid and analytical since the linking is an
incremental and light-weight process.
 High Performance − With the use of Just-In-

Time compilers, Java enables high performance.


 Distributed − Java is designed for the
distributed environment of the internet.
 Dynamic − Java is considered to be more
dynamic than C or C++ since it is designed to
adapt to an evolving environment. Java
programs can carry extensive amount of run-
time information that can be used to verify and
resolve accesses to objects on run-time.
History of Java
James Gosling initiated Java language project in
June 1991 for use in one of his many set-top box
projects. The language, initially called ‘Oak’ after
an oak tree that stood outside Gosling's office, also
went by the name ‘Green’ and ended up later being
renamed as Java, from a list of random words.
Sun released the first public implementation as Java
1.0 in 1995. It promised Write Once, Run
Anywhere (WORA), providing no-cost run-times
on popular platforms.
On 13 November, 2006, Sun released much of Java
as free and open source software under the terms of
the GNU General Public License (GPL).
On 8 May, 2007, Sun finished the process, making
all of Java's core code free and open-source, aside
from a small portion of code to which Sun did not
hold the copyright.
Tools Needed to java
For performing the examples discussed in this
tutorial, you will need a Pentium 200-MHz
computer with a minimum of 64 MB of RAM (128
MB of RAM recommended).
We will also need the following softwares −
 Linux 7.1 or Windows xp/7/8 operating system
 Java JDK 8
 Microsoft Notepad or any other text editor
This tutorial will provide the necessary skills to
create GUI, networking, and web applications using
Java.
Java Virtual Machine (JVM), Difference JDK,
JRE & JVM – Core Java
Java is a high level programming language. A
program written in high level language cannot be run
on any machine directly. First, it needs to be
translated into that particular machine language.
The javac compiler does this thing, it takes java
program (.java file containing source code) and
translates it into machine code (referred as byte code
or .class file).
Java Virtual Machine (JVM) is a virtual machine
that resides in the real machine (your computer) and
the machine language for JVM is byte code. This
makes it easier for compiler as it has to generate byte
code for JVM rather than different machine code for
each type of machine. JVM executes the byte code
generated by compiler and produce output. JVM is
the one that makes java platform independent.
So, now we understood that the primary function
of JVM is to execute the byte code produced by
compiler. Each operating system has different
JVM, however the output they produce after
execution of byte code is same across all
operating systems. Which means that the byte
code generated on Windows can be run on Mac
OS and vice versa. That is why we call java as
platform independent language. The same thing
can be seen in the diagram below:

Local Environment Setup


If you are still willing to set up your environment
for Java programming language, then this section
guides you on how to download and set up Java on
your machine. Following are the steps to set up the
environment.
Java SE is freely available from the link Download
Java. You can download a version based on your
operating system.
Follow the instructions to download Java and run
the .exe to install Java on your machine. Once you
installed Java on your machine, you will need to set
environment variables to point to correct installation
directories
Setting Up the Path for Windows
Assuming you have installed Java in c:\Program
Files\java\jdk directory −
 Right-click on 'My Computer' and select
'Properties'.
 Click the 'Environment variables' button under

the 'Advanced' tab.


 Now, alter the 'Path' variable so that it also

contains the path to the Java executable.


Example, if the path is currently set to 'C:\
WINDOWS\SYSTEM32', then change your
path to read 'C:\WINDOWS\SYSTEM32;c:\
Program Files\java\jdk\bin'.
When we consider a Java program, it can be defined
as a collection of objects that communicate via
invoking each other's methods. Let us now briefly
look into what do class, object, methods, and
instance variables mean.
 Object − Objects have states and behaviors.

Example: A dog has states - color, name, breed


as well as behavior such as wagging their tail,
barking, eating. An object is an instance of a
class.
 Class − A class can be defined as a
template/blueprint that describes the
behavior/state that the object of its type
supports.
 Methods − A method is basically a behavior. A

class can contain many methods. It is in


methods where the logics are written, data is
manipulated and all the actions are executed.
 Instance Variables − Each object has its unique

set of instance variables. An object's state is


created by the values assigned to these instance
variables.
First Java Program
Let us look at a simple code that will print the
words Hello World.
Example

publicclassMyFirstJavaProgram{

/* This is my first java program.


* This will print 'Hello World' as the output
*/

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.

 Save the file as: MyFirstJavaProgram.java.


 Open a command prompt window and go to the
directory where you saved the class. Assume it's
C:\.
 Type 'javac MyFirstJavaProgram.java' and press

enter to compile your code. If there are no


errors in your code, the command prompt will
take you to the next line (Assumption : The path
variable is set).
 Now, type ' java MyFirstJavaProgram ' to run

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

means identifier Hello and hello would have


different meaning in Java.
 Class Names − For all class names the first

letter should be in Upper Case. If several words


are used to form a name of the class, each inner
word's first letter should be in Upper Case.
Example: class MyFirstJavaClass
 Method Names − All method names should
start with a Lower Case letter. If several words
are used to form the name of the method, then
each inner word's first letter should be in Upper
Case.
Example: public void myMethodName()
 Program File Name − Name of the program
file should exactly match the class name.
When saving the file, you should save it using
the class name (Remember Java is case
sensitive) and append '.java' to the end of the
name (if the file name and the class name do not
match, your program will not compile).
But please make a note that in case you do not
have a public class present in the file then file
name can be different than class name. It is also
not mandatory to have a public class in the file.
Example: Assume 'MyFirstJavaProgram' is the
class name. Then the file should be saved
as 'MyFirstJavaProgram.java'
public static void main(String args[]) − Java
program processing starts from the main()
method which is a mandatory part of every Java
program.
Data Types in Java
Data types specify the different sizes and values that
can be stored in the variable. There are two types of
data types in Java:
1.Primitive data types: The primitive data types
include boolean, char, byte, short, int, long, float
and double.
2.Non-primitive data types: The non-primitive
data types include Classes, Interfaces, and
Arrays.
Java Primitive Data Types
In Java language, primitive data types are the
building blocks of data manipulation. These are the
most basic data types available in Java language.

Java is a statically-typed programming language. It


means, all variables must be declared before its use.
That is why we need to declare variable's type and
name.

There are 8 types of primitive data types:


o boolean data type
o byte data type
o char data type
o short data type
o int data type
o long data type
o float data type
o double data type

Data Type Default Value Default size

Boolean false 1 bit

Char '\u0000' 2 byte

Byte 0 1 byte

Short 0 2 byte

Int 0 4 byte
Long 0L 8 byte

Float 0.0f 4 byte

Double 0.0d 8 byte

Boolean Data Type


The Boolean data type is used to store only two
possible values: true and false. This data type is used
for simple flags that track true/false conditions.
The Boolean data type specifies one bit of
information, but its "size" can't be defined precisely.
Example: Boolean one = false
Byte Data Type
The byte data type is an example of primitive data
type. It isan 8-bit signed two's complement integer.
Its value-range lies between -128 to 127 (inclusive).
Its minimum value is -128 and maximum value is
127. Its default value is 0.
The byte data type is used to save memory in large
arrays where the memory savings is most required. It
saves space because a byte is 4 times smaller than an
integer. It can also be used in place of "int" data
type.
Example: byte a = 10, byte b = -20
Short Data Type
The short data type is a 16-bit signed two's
complement integer. Its value-range lies between -
32,768 to 32,767 (inclusive). Its minimum value is -
32,768 and maximum value is 32,767. Its default
value is 0.
The short data type can also be used to save memory
just like byte data type. A short data type is 2 times
smaller than an integer.
Example: short s = 10000, short r = -5000
Int Data Type
The int data type is a 32-bit signed two's
complement integer. Its value-range lies between -
2,147,483,648 (-2^31) to 2,147,483,647 (2^31 -1)
(inclusive). Its minimum value is - 2,147,483,648and
maximum value is 2,147,483,647. Its default value is
0.
The int data type is generally used as a default data
type for integral values unless if there is no problem
about memory.
Example: int a = 100000, int b = -200000
Long Data Type
The long data type is a 64-bit two's complement
integer. Its value-range lies between -
9,223,372,036,854,775,808(-2^63) to
9,223,372,036,854,775,807(2^63 -1)(inclusive). Its
minimum value is - 9,223,372,036,854,775,808and
maximum value is 9,223,372,036,854,775,807. Its
default value is 0. The long data type is used when
you need a range of values more than those provided
by int.
Example: long a = 100000L, long b = -200000L
Float Data Type
The float data type is a single-precision 32-bit IEEE
754 floating point.Its value range is unlimited. It is
recommended to use a float (instead of double) if
you need to save memory in large arrays of floating
point numbers. The float data type should never be
used for precise values, such as currency. Its default
value is 0.0F.
Example: float f1 = 234.5f
Double Data Type
The double data type is a double-precision 64-bit
IEEE 754 floating point. Its value range is unlimited.
The double data type is generally used for decimal
values just like float. The double data type also
should never be used for precise values, such as
currency. Its default value is 0.0d.
Example: double d1 = 12.3
Char Data Type
The char data type is a single 16-bit Unicode
character. Its value-range lies between '\u0000' (or 0)
to '\uffff' (or 65,535 inclusive).The char data type is
used to store characters.
Example: char letterA = 'A'
Why char uses 2 byte in java and what is \u0000 ?
It is because java uses Unicode system not ASCII
code system. The \u0000 is the lowest range of
Unicode system. To get detail explanation about
Unicode visit next page.
Type conversion in Java with Examples
When you assign value of one data type to another,
the two types might not be compatible with each
other. If the data types are compatible, then Java will
perform the conversion automatically known as
Automatic Type Conversion and if not then they
need to be casted or converted explicitly. For
example, assigning an int value to a long variable.
Widening or Automatic Type Conversion
Widening conversion takes place when two data
types are automatically converted. This happens
when:
 The two data types are compatible.

 When we assign value of a smaller data type to a

bigger data type.


For Example, in java the numeric data types are
compatible with each other but no automatic
conversion is supported from numeric type to char or
boolean. Also, char and boolean are not compatible
with each other.

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

automatic conversion cannot be done.


 Here, target-type specifies the desired type to

convert the specified value to.

char and number are not compatible with each other.


Let’s see when we try to convert one into other.
//Java program to illustrate incompatible
data
// type for explicit type conversion
Public class Test
{
Public static void main(String[] args)
{
Char ch = 'c';
Int num = 88;
ch = num;
}
}
Error:
7: error: incompatible types: possible lossy
conversion from int to char
ch = num;
^
1 error
How to do Explicit Conversion?
Example:

//Java program to illustrate explicit type


conversion
class Test
{
Public static void main(String[] args)
{
Double d = 100.04;

//explicit type casting


Long l = (long)d;
//explicit type casting
Int i = (int)l;
System.out.println("Double value"+d);
//fractional part lost
System.out.println("Long value "+l);
//fractional part lost
System.out.println("Int value "+i);
}
}
Output:
Double value 100.04
Long value 100
Int value 100
While assigning value to byte type the fractional part
is lost and is reduced to modulo 256(range of byte).
Example:
//Java program to illustrate Conversion of
int and double to byte
Class Test
{
Public static void main(String args[])
{ byte b;
inti = 257;
doubled = 323.142;
System.out.println("Conversion of int
to byte.");
//i%256
b = (byte) i;
System.out.println("i = "+ i + " b = "+
b);
System.out.println("\nConversion of
double to byte.");

//d%256
b = (byte) d;
System.out.println("d = "+ d + " b= "+
b);
}
}
Output:
Conversion of int to byte.
i = 257 b = 1

Conversion of double to byte.


d = 323.142 b = 67

Type Casting

Type casting is a way to convert a variable from one


data type to another data type. For example, if you
want to store a long value into a simple integer then
you can type cast long to int. You can convert
values from one type to another using the cast
operator. Its syntax is as follows −
type_name(expression)
Example
Consider the following example where the cast
operator causes the division of one integer variable
by another to be performed as a floating number
operation.
package main
import"fmt"
func main(){
var sum int=17
var count int=5
var mean float32
mean= float32(sum)/float32(count)
fmt.Printf("Value of mean : %f\n",mean)
}
When the above code is compiled and executed, it
produces the following result −
Value of mean : 3.400000
Conditional Statements In Java
Let’s see the following conditional statements
1. if statement
2. nested if statement
3. if-else statement
4. if-else-if statement
5. Switch Case Statement
if statement:
The if statement is the most basic of all the control
flow statements. The if statement tells our program
to execute a certain section of code only if a
particular test evaluates to true.
SYNTAX:
1 if(condition){
2 Statement(s);
3}
Sample Program:
packageClassThreeControlFlowStatements;
public class IfStatement{
4 public static void main(String[] args){
5
6 int num=100;
7
8 if(num<=100){
9 System.out.println("Value of num is
10 "+num);
11 }
12
13 }
14
15 }
Nested if statement:

An if statement inside another the statement. If the


outer if condition is true then the section of code
under outer if condition would execute and it goes to
the inner if condition. If inner if condition is true
then the section of code under inner if condition
would execute.
Syntax:
if(condition_1){
Statement1(s);
if(condition_2){
Statement2(s);
}
}
SAMPLE PROGRAM
1 packageClassThreeControlFlowStatements;
2
3 System.out.println("n is even number
4 n="+n);
5}
6
7
8
9
10
11
12
13
14
15
16
17
18
19
if-else statement:
If a condition is true then the section of code under if
would execute else the section of code under else
would execute.
Syntax:
1 if(condition){
2 Statement(s);
3}
4 else{
5 Statement(s);
6}
Sample Program:

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.

The while statement continually executes a block of


statements while a particular condition is true.
Syntax:
1 while(expression){
2 // statement(s)
3}
If the expression of while statement evaluates to
true, then it executes the statement(s) in the while
block. The while statement continues testing the
expression and executing its block until the
expression evaluates to false.
Sample Program:

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.

Example: A dog has states - color, name, breed


as well as behaviors – wagging the tail, barking,
eating. An object is an instance of a class.
 Class − A class can be defined as a
template/blueprint that describes the
behavior/state that the object of its type support.
Objects in Java
Let us now look deep into what are objects. If we
consider the real-world, we can find many objects
around us, cars, dogs, humans, etc. All these objects
have a state and a behavior.
If we consider a dog, then its state is - name, breed,
color, and the behavior is - barking, wagging the
tail, running.
If you compare the software object with a real-
world object, they have very similar characteristics.
Software objects also have a state and a behavior. A
software object's state is stored in fields and
behavior is shown via methods.
So in software development, methods operate on the
internal state of an object and

the object-to-object communication is done via


methods.
Classes in Java
A class is a blueprint from which individual objects
are created.
Following is a sample of a class.
Example
publicclassDog{
String breed;
int age;
String color;

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

declared within a class, outside any method,


with the static keyword.
A class can have any number of methods to access
the value of various kinds of methods. In the above
example, barking(), hungry() and sleeping() are
methods.
Following are some of the important topics that
need to be discussed when looking into classes of
the Java Language.
Creating an Object
As mentioned previously, a class provides the
blueprints for objects. So basically, an object is
created from a class. In Java, the new keyword is
used to create new objects.
There are three steps when creating an object from a
class −
 Declaration − A variable declaration with a

variable name with an object type.


 Instantiation − The 'new' keyword is used to

create the object.


 Initialization − The 'new' keyword is followed

by a call to a constructor. This call initializes


the new object.
Following is an example of creating an object −
Example
Public class Puppy{
Public Puppy(String name){
// This constructor has one parameter, name.
System.out.println("Passed Name is :"+ name );
}
Public static void main(String[] args){
Puppy myPuppy=new Puppy("tommy");
Puppy p1=new Puppy(“dghtfh”);
}
}
If we compile and run the above program, then it
will produce the following res

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.

from where it can be accessed in your application.


In Java, there 4 type of the access specifiers.
 public: accessible in all class in your

application.
 protected: accessible within the class in which it

is defined and in its subclass(es)


 private: accessible only within the class in


which it is defined.
 default (declared/defined without using any

modifier) : accessible within same class and


package within which its class is defined.
 The return type : The data type of the value
returned by the method or void if does not return a
value.
 Method Name : the rules for field names apply to
method names as well, but the convention is a
little different.
 Parameter list : Comma separated list of the input
parameters are defined, preceded with their data
type, within the enclosed parenthesis. If there are
no parameters, you must use empty parentheses ().
 Exception list : The exceptions you expect by the
method can throw, you can specify these
exception(s).
 Method body : it is enclosed between braces. The
code you need to be executed to perform your
intended operations.

Method signature: It consists of the method name


and a parameter list (number of parameters, type of
the parameters and order of the parameters). The
return type and exceptions are not considered as part
of it.
Method Signature of above function:
max(int x, int y)
How to name a Method?: A method name is
typically a single word that should be a verb in
lowercase or multi-word, that begins with a verb in
lowercase followed by adjective, noun….. After the
first word, first letter of each word should be
capitalized. For example, findSum,
computeMax, setX and getX
Generally, A method has a unique name within the
class in which it is defined but sometime a method
might have the same name as other method names
within the same class as method overloading is
allowed in Java.
Calling a method
The method needs to be called for using its
functionality. There can be three situations when a
method is called:
A method returns to the code that invoked it when:
 It completes all the statements in the method

 It reaches a return statement

 Throws an exception

// Program to illustrate methodsin java


importjava.io.*;
class Addition {
int sum = 0;
public int addTwoInt(int a, int b)
{
sum = a + b;

return sum;
}

classGFG {
publicstaticvoidmain (String[] args) {

// creating an instance of Addition


class
Addition add = newAddition();

// calling addTwoInt() method to add


two integer using instance created
// in above step.
ints = add.addTwoInt(1,2);
System.out.println("Sum of two
integer values :"+ s);
}
}
Output :
Sum of two integer values :3
See the below example to understand method call in
detail :
filter_none
edit
play_arrow
brightness_4
// Java program to illustrate different ways
of calling a method
importjava.io.*;

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");

// calling m2() method within the same


class.
this.m2();
// statements to be executed if any
return1;
}

// It doesn't return anything as


// return type is 'void'.
publicvoidm2()
{

System.out.println("In method m2
came from method m1");
}
}

classGFG
{
publicstaticvoidmain(String[] args)
{
// Creating an instance of the class
Test obj = newTest();

// Calling the m1() method by the


object created in above step.
inti = obj.m1();
System.out.println("Control returned
after method m1 :"+ i);

// Call m2() method


// obj.m2();
intno_of_objects = Test.get();

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

Method Overloading in Java


If a class has multiple methods having same name
but different in parameters, it is known as Method
Overloading.
If we have to perform only one operation, having
same name of the methods increases the readability
of the program.
Suppose you have to perform addition of the given
numbers but there can be any number of arguments,
if you write the method such as a(int,int) for two
parameters, and b(int,int,int) for three parameters
then it may be difficult for you as well as other
programmers to understand the behavior of the
method because its name differs.
So, we perform method overloading to figure out the
program quickly.

Advantage of method overloading


Method overloading increases the readability of the
program.
Different ways to overload the method
There are two ways to overload the method in java
1.By changing number of arguments
2.By changing the data type

In java, Method Overloading is not possible by


changing the return type of the method only.

1) Method Overloading: changing no. of arguments


In this example, we have created two methods, first
add() method performs addition of two numbers and
second add method performs addition of three
numbers.
In this example, we are creating static methods so
that we don't need to create instance for calling
methods.
1.class Adder{
2.static int add(int a,int b){return a+b;}
3.static int add(int a,int b,int c){return a+b+c;}
4.}
5.class TestOverloading1{
6.public static void main(String[] args){
7.System.out.println(Adder.add(11,11));
8.System.out.println(Adder.add(11,11,11));
9.}}
Test it Now
Output:
22

33

2) Method Overloading: changing data type of


arguments
In this example, we have created two methods that
differs in data type. The first add method receives
two integer arguments and second add method
receives two double arguments.
1.class Adder{
2.static int add(int a, int b){return a+b;}
3.static double add(double a, double b){return a+b;
}
4.}
5.class TestOverloading2{
6.public static void main(String[] args){
7.System.out.println(Adder.add(11,11));
8.System.out.println(Adder.add(12.3,12.6));
9.}}
Test it Now
Output:
22
24.9

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.

Refer constructor overloading with example for


more details with example.
Java Copy Constructor
A copy constructor is used for copying the values of
one object to another object.
Class JavaExample{
String web;
JavaExample(String w){
web= w;
}

/* This is the Copy Constructor, it


* copies the values of one object
* to the another object (the object
* that invokes this constructor)
*/
JavaExample(JavaExample je){
web= je.web;
}
Void disp(){
System.out.println("Website: "+web);
}

Public static void main(String args[]){


JavaExample obj1 =new
JavaExample("BeginnersBook");
/* Passing the object as an argument to the
constructor
* This will invoke the copy constructor
*/
JavaExample obj2 =newJavaExample(obj1);
obj1.disp();
obj2.disp();
}
}
Output:
Website: BeginnersBook
Website: Beginners Book

You might also like