0% found this document useful (0 votes)
25 views64 pages

Java Basics:: Unit-I

The document provides an overview of Java programming, covering its history, features, and the Java Development Kit (JDK) tools. It explains the concepts of Java applications and applets, the Java Virtual Machine (JVM), and the Java Runtime Environment (JRE), while highlighting Java's portability and security features. Additionally, it discusses Java's data types, variable scopes, and the differences between Java and C++, emphasizing Java's strong typing and object-oriented nature.

Uploaded by

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

Java Basics:: Unit-I

The document provides an overview of Java programming, covering its history, features, and the Java Development Kit (JDK) tools. It explains the concepts of Java applications and applets, the Java Virtual Machine (JVM), and the Java Runtime Environment (JRE), while highlighting Java's portability and security features. Additionally, it discusses Java's data types, variable scopes, and the differences between Java and C++, emphasizing Java's strong typing and object-oriented nature.

Uploaded by

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

UNIT-I

Java Basics:
History of JAVA
Java is a high level programming Language. It was introduced by ―SUN Microsystems‖ in June
1995. It was developed by a team under James Gosling. Its original name was ―OAK‖ and later
renamed to Java. Java has become the standard for Internet applications.
Since the Internet consists of different types of computers and operating systems. A common
language needed to enable computers. To run programs that run on multiple plot forms.
Java is Object-Oriented language built on C and C++. It derives its syntax from C and its
Object-Oriented features are influenced by C++.
Java can be used to create two types of programs
 Applications
 Applets.
An application is a prg.that runs on the user‗s computers under the operating system.
An Applet is a small window based prg.that runs on HTML page using a java enabled web
browser like internet Explorer, Netscape Navigator or an Applet Viewer.

The Java Programming Environment


Applets are java programs. That run as part of a web page and they depend on a web browser in
order to run. Applications are programs that are stored on the user‗s system and they do not need
a web browser in order to run.
The Java programming environment includes a number of development tools to develop applet
and application. The development tools are part of the system known as “Java Development
Kit” or “ JDK”. The JDK include the following.
1. Packages that contain classes.
2. Compiler
3. Debugger
JDK (java development tool kit):
It is a software package from the sun micro systems where a new package JFC( java foundation
classes) was available as a separate package

JDK provides tools in the bin directory of JDK and they are as follows:
Javac: Javac is the java compiler that translates the source code to byte codes. That is, it
converts the source file. Namely the .java file to .class file.
Java: The java interpreter which runs applets and Applications by reading and interpreting the
byte code files. That is, it executes the .class file.
Javadoc: Javadoc is the utility used to produce documentation for the classes from the java files.
JDB: JDB is a debugging tool.
The way these tools are applied to build and run application programs is as follows:
The source code file is created using a text editor and saved with a .java (with Extension). The
source code is compiled using the java compiler javac. This translates source code to byte
codes. The compiled code is executed using the java interpreter java.
UNIT-I

JVM (JAVA VIRTUAL MACHINE)


Java is both compiled and an interpreted lang. First the java compiler translates source code
into the byte code instructions. In the next stage the java interpreter converts the byte code
instructions to machine code. This machine within the computer‗ is known as the “Java Virtual
Machine” or JVM.
The JVM can be thought as a mini operating system that forms a layer of abstraction where the
underlying hardware. The portability feature of the .class file helps in the execution of the prg
on any computer with the java virtual machine. This helps in implementing the “write once and
run anywhere” feature of java.

JAVA RUNTIME ENVIRONMENT


JRE consists of the java virtual machine. The java plot form core classes and supporting files. It
is the run time part of the java Development Kit. No compiler, no debugger, no tools.
Loding the .class files: Performed by the ‗ class loader‗ .
Verifying bytecode: Performed by the ‗ bytecode verifier‗ .
Executing the code : Performed by the runtime interpreter.

JIT (JUST – IN – TIME)


Just – In – Time (JIT) compiler is a program that runs java bytecode into instructions that can be
sent directly to the processor. (Machine code).
Steps to execute a java prg:
? Open any editor such as notepad
? Type the source code
? Save it with .java extension (File Name and class name must be same)
? Compile it
? Run it
UNIT-I

Steps to compile a java prg:


? Open Dos prompt
? Set the path Ex: path=c:\jdk1.2.2\bin and press enter key
? Move to your working directory/folder
? Compile the prg Ex: javac filename.java
? Run the prg Ex: java filename

IN THE JAVA PROGRAM:


public: It indicates that main() can be called outside the class.
static: It is an access specifier, which indicates that main() can be called directly without
creating an object to the class.
void: It indicates that the method main() doesn‗ t return a value.
main(): It is a method which is an entry point into the java prg. When you run a java prg.main()
is called first.
String args [ ]: String is a class, which belongs to java.lang package. It can be used as a string
data type in java.
args[]: It is an array of string type. It is used to store command line args.
System: It is a class, which belongs to java.lang package.
out: It is an output stream object, which is a member of System class.
println(): It is a method supported by the output stream object ―out‖. It is used to display any kind
of output on the screen. It gives a new line after printing the output.
print(): It is similar to println(). But doesn‗ t give a new line after printing the output.

Java‟s Byte code:


The key that allows java to solve the both security and portability problems is that the output of a
java compiler is not executable code rather it is byte code. Byte code is highly optimized set of
instructions designed to be executed by java runtime systems, which is called JVM.
Byte codes are instructions that are generated for a virtual machine. A virtual machine is a
program that processes these generalized instructions to machine specific code.
Differences of JAVA from C++
 No typedefs, defines or preprocessors
 No header files
 No structures and unions
 No enums (enum class is there)
 No functions – only methods in classes
 No multiple inhehitance trough class (achieve using interface)
 No operator overloading (except ‗+‗ for string concatenation)
 No automatic type conversions (except for primitive types)
 No pointers
UNIT-I

Java Buzzwords or Features of Java:


No discussion of the genesis of Java is complete without a look at the Java buzzwords. Although
the fundamental forces that necessitated the invention of Java are portability and security, other
factors also played an important role in mol ding the final form of the language. The key
considerations were summed up by the Java team in the following list of buzzwords:
1. Simple: Java follows the syntax of C and Object Oriented principles of C++. It eliminates the
complexities of C and C++. Therefore, Java has been made simple.

2. Object-Oriented: It is an Object-Oriented programming language. The object model in Java


is simple. Although influenced by its procedures. It was designed to be source code compatible
with any other language.
3. Plot form Independent: Plot form is the combination of operating system and
microprocessor. Java programming works in all plot forms. It is achieved by JVM (Java Virtual
Machine). The philosophy of java is ―Write Once, Run anywhere‖ (WORA).
4. Robust: Java is strictly a typed language. It has both a compiler and an interpreter. Compiler
checks code at run time and garbage collection is taking care of by java automatically. Thus it is
a robust language.
5. Secure: java developers have taken all care to make it a secure programming language.
For Ex. Java Applets are restricted from Disk I/O of local machine.
6. Distributed: Java is designed for the distributed environment of the Internet. It handles
TCP/IP protocols. Java‗s remote method invocation (RMI) make distributed programming
Possible.
UNIT-I

7. Multithreaded: Java was designed to meet the real-world requirement. To achieve this, java
supports multithreaded programming. It is the ability to run any things simultaneously.
8. Dynamic: That is run time. This makes it possible to dynamically link code in a safe and
secure manner.
9. Architecture-Neutral
A central issue for the Java designers was that of code longevity and portability. One of the main
problems facing programmers is that no guarantee exists that if you write a program today, it will
run tomorrow—even on the same machine.
Operating system upgrades, processor upgrades, and changes in core system resources can all
combine to make a program malfunction. The Java Virtual Machine (JVM) in an attempt to alter
this situation. Their goal was ―write once; run anywhere, anytime, forever.

10. Interpreted and High Performance


Java enables the creation of cross-platform programs by compiling into an intermediate
representation called Java byte code. This code can be interpreted on any system that provides a
Java Virtual Machine. It would be easy to translate directly into native machine code for very
high performance by using a just-in-time compiler.

Comments: There are 3 types of comments defined by java. Those are Single line comment,
multilane comment and the third type is called documentation comment. This type of comment is
used to produce an HTML file that documents your prg.
// this is single line comment.
/* this multiple
line comment*/
/** this documentation comment */

Key words:
Keywords are the words. Those have specifics meaning in the compiler. Those are called
keywords. There are 49 reserved keywords currently defined in the java language. These
keywords cannot be used as names for a variable, class or method. Those are,

Java Is a Strongly Typed Language


It is important to state at the outset that Java is a strongly typed language. Indeed, part of Java‗s
safety and robustness comes from this fact. Let‗s see what this means.
UNIT-I

First, every variable has a type, every expression has a type, & every type is strictly defined.
Second, all assignments, whether explicit or via parameter passing in method calls, are checked
for type compatibility. There are no automatic coercions or conversions of conflicting types as in
some languages.
The Java compiler checks all expressions and parameters to ensure that the types are compatible.
Any type mismatches are errors that must be corrected before the compiler will finish compiling
the class.
For example, in C/C++ you can assign a floating-point value to an integer as shown below
int n=12.345;
where in the above case the integer variable holds only the round part of the assigned fraction
value as n=12.
In Java, you cannot. Also, in C there is not necessarily strong type-checking between a
parameter and an argument. In Java, there is.
DATA TYPES:
The data, which gives to the computer in different types, are called Data Types or Storage
representation of a variable is called Data Type. Java defines 8 types of data: byte, short, int,
long, float, double, char and Boolean.
These can be put in Four types:
Integer: this group includes byte, short, int & long, which are whole valued signed numbers.
Floating-point numbers: float & double, which represents numbers with fractional precision.
Character: This represents symbols in a character set, like letters and numbers.
Boolean: This is a special type for representing true / false values.

Examples of double and char


class FindSqrt class CharDemo {
{ public static void main(String args[]) {
public static void main(String args[]) char ch1, ch2;
{ ch1 = 88; // code for X
double d1=25,d2=34; ch2 = 'Y';
System.out.println("Sqrt of d1 System.out.print("ch1 and ch2: ");
is:"+Math.sqrt(d1)); System.out.println(ch1 + " " + ch2);
System.out.println("Sqrt of d2 }
is:"+Math.sqrt(d2)); }
} This program displays the following output:
} ch1 and ch2: X Y
UNIT-I

Examples of boolean
class BoolTest b = false;
{ if(b) {
public static void main(String args[]) System.out.println("This is not executed.");}
{ System.out.println("10 > 9 is " + (10 > 9));
boolean b; }
b = false; }
System.out.println("b is " + b); Output:
b = true; b is false
System.out.println("b is " + b); b is true
if(b){ This is executed.
System.out.println("This is executed."); } 10 > 9 is true
Variables:
The variable is the basic unit of storage in a Java program. A variable is defined by the
combination of an identifier, a type, and an optional initializer. In addition, all variables have a
scope, which defines their visibility, and a lifetime. In Java, all variables must be declared before
they can be used. The basic form of a variable declaration is shown here:
type identifier [ = value][, identifier [= value] ...];
Ex: int a, b, c; // declares three ints, a, b, and c.
int d = 3, e, f = 5; // declares three more ints
byte z = 22; // initializes z.
double pi = 3.14159; // declares an approximation of pi.
char x = 'x'; // the variable x has the value 'x'.

Constant identifiers:
Final keyword is used for constants. Constant identifiers consist of all capital letters. Internal
words are separated by an underscore (_).
Example: final double TAX_RATE = .05

The Scope and Lifetime of Variables:


All of the variables used till now have been declared at the start of the main( ) method. However,
Java allows variables to be declared within any block. A block is begun with an opening curly
brace and ended by a closing curly brace. A block defines a scope.
Most other computer languages define two general categories of scopes: global and local.
The scope defined by a method begins with its opening curly brace.
Objects declared in the outer scope will be visible to code within the inner scope. However, the
reverse is not true. Objects declared within the inner scope will not be visible outside it.
To understand the effect of nested scopes, consider the following program:
// demonstrate block scope. if(x == 10)
class Scope { // start new scope
{ int y = 20; // known only to this block
public static void main(String args[])
{ // x and y both known here.
int x; // code within main System.out.print("x and y:" +x+ " " + y);
x = 10; x = y * 2;
UNIT-I

} }
y = 100; // Error! y not known here }
// x is still known here. Output: x and y: 10 20 x is 40
System.out.print("\tx is " + x);
Types of variables: Java has 4 different kinds of variables
 local variables
 parameter variables
 class variables
 instance variables

Local variables:
A local variable will exists as long as the method in which they have been created is still running
As soon as the method terminates, all the local variables inside the method are destroyed.
Example: Scope of local variables:
class SomeClass class Scope2
{ {
public static void main(String args[]) public static void main(String args[ ]) {
{ void show(){
double x; double r;
…....................Local variables r=3.14;
int y; }
} System.out.println(r ); //Causes error is not
} } accessible outside the block
}
Non-overlapping (or disjoint) scopes:
It is possible to declare two variables with the same name in two different block scopes as shown
below
class Scope {
public static void main(String args[]) {
-------
{ double r;
{
String r;
} }
}
}

Parameter variables:
A parameter variable is used to store information that is being passed from the location of the
method call into the method that is called.
class ToolBox
{ a=1.0 b=2.0
public static double min(double a,double b) //Parameter variables
{ ……………….. }
}
class MyProgram
{
UNIT-I

public static void main(String args[]) {


double r;
r=ToolBox.min(1.0,2.0);
} }
Life and scope of parameter variable:
The life time of a parameter variable is the entire body of the method
• A parameter variable behaves like a local variable that is defined at the Start of the method
Class variables:
Variables that are declared with the keyword static are called as class variables
Life of class variables: Class variables exists for the entire execution of the java program
Scope of class variables: The scope can be public
class StaticData
{
static int a=10,b=20; //Access these variables through class name, because of static.
}
class StaticDemo
{
public static void main(String args[])
{
int sum=StaticData.a+StaticData.b;
System.out.println("sum is"+sum);
} }

Instance variables:
Non static variables that are declared inside a class are called as instance variables.
class StaticData
{
int a=10,b=20; //instance variables of StaticData class
}
Life and scope of Instance variables:
It is limited only the object specified upon the class

Literals
Integer Literals
Integers are probably the most commonly used type in the typical program. Any hole number
value is an integer literal. Examples are 1, 2, 3, and 42.

Integer literals are classified into three types as


 Decimal literal  Octal literal  Hexadecimal literal

Decimal literals
These are all decimal values, meaning they are describing a base 10 number. There are two other
bases which can be used in integer literals
Example: int n=10;
UNIT-I

Octal literals
Octal (base eight). Octal values are denoted in Java by a leading zero. Normal decimal numbers
cannot have a leading zero.
Thus, the seemingly valid value 09 will produce an error from the compiler, since 9 is outside of
octal‟s 0 to 7 range.
Example: int n=07;

Hexadecimal literals:
Hexadecimal (base 16), A more common base for numbers used by programmers is
hexadecimal, which matches cleanly with modulo 8 word sizes, such as 8, 16, 32, and 64 bits.
You signify a hexadecimal constant with a leading zero-x, (0x or 0X). The range of a
hexadecimal digit is 0 to 15, so A through F (or a through f ) are substituted for 10 through 15.
Example: int n=0xfff;
Example Program:
class Literal System.out.print("decimal literal is:"+dec);
{ System.out.println("octal literal is:"+oct);
public static void main(String args[]) System.out.println("hexadecimal is:"+hex);
{ }
int dec=10,oct=07,hex=0xff; }

Floating-Point Literals
Floating-point numbers represent decimal values with a fractional component.
Example: float f=12.346f (or) 12.346F;
double d=34.5678d (or) 34.5678D;

Boolean Literals
Boolean literals are simple. There are only two logical values that a boolean value can have, true
and false. The true literal in Java does not equal 1, nor does the false literal equal 0.

Character Literals Escape Sequence Meaning


\n new line
Characters in Java are indices into the Unicode
\t horizontal tab
character set. They are 16-bit values. A literal \v vertical tab
character is represented inside a pair of single quotes. \b Backspace
All of the visible ASCII characters can be directly \r carriage return
entered inside the quotes, such as ‗a‗, ‗z‗, and ‗@‗. \f form feed
\a Bell
String Literals \\ text literal
String literals in Java are enclosing a sequence of \' ' char literal
characters between a pair of double quotes. \" " String literal
\ddd Octal character(ddd)
Ex: ―Hello World‖ ―two\nlines‖ \uxxxx Hexa character (xxxx)
―\‖This is in quotes\‖‖
UNIT-I

Java Naming conventions


Java naming convention is a rule to follow as you decide what to name your identifiers such as
class, package, variable, constant, method etc. But, it is not forced to follow. So, it is known as
convention not rule.
All the classes, interfaces, packages, methods and fields of java programming language are given
according to java naming convention.

Advantage of naming conventions in java


By using standard Java naming conventions, you make your code easier to read for yourself and
for other programmers. Readability of Java program is very important.
Name Convention
class name Should start with uppercase letter and be a noun e.g. String, Color,
Button, System, Thread etc. Ex: class MyClass

interface name Should start with uppercase letter and be an adjective


e.g. Runnable, Remote, ActionListener etc.
method name Should start with lowercase letter and be a verb
e.g. actionPerformed(), main(), print(), println() etc.
variable name Should start with lowercase letter e.g. firstName, orderNumber etc.

package name Should be in lowercase letter e.g. package java.lang;

constants name Should be in uppercase letter. e.g. RED, YELLOW,


MAX_PRIORITY etc. e.g. final double TAX_RATE = .05

Camel Case in java naming conventions


Java follows camelcase syntax for naming the class, interface, method and variable. If name is
combined with two words, second word will start with uppercase letter always.
e.g. actionPerformed(), firstName, ActionEvent, ActionListener etc.

OPERATORS:
Operator is a Symbol. Java provides a rich set of operators as

The Arithmetic Operators:


Arithmetic operators are used in mathematical expressions in the same way that they are used in
algebra. The arithmetic operators are: + - * / %
The Relational Operators: It tells the relationship b/w two operands e.g., a>b, a<b, a==b, a<=b , a>=b
== (equal to),!= (not equal to),> (greater than),< (less than),>= (greater than or equal to),<=
(less than or equal to)
The Assignment Operators(=):Thisoperatoris usedto assignthevalueof a variable.E.g. a=4
Short hand assignment operator: += -= *= /= %= E.g. a+=4 (a=a+4)
UNIT-I

The Bitwise Operators:


Bitwise operator works on bits and performs bit-by-bit operation. Assume if a = 60; b = 13; now in
binary format they will be as follows: a = 0011 1100
Binary Left Shift Operator: << (left shift) b = 0000 1101
It is moved left by the number of bits specified by the right operand. -----------------
a&b = 0000 1100
Example: A << 2 will give 240 which is 1111 0000
a|b = 0011 1101
Binary Right Shift Operator: >> (right shift) a^b = 0011 0001
It is moved right by the number of bits specified by the right operand. ~a = 1100 0011
Example: A >> 2 will give 15 which is 1111
Shift right zero fill operator : >>> (zero fill right shift)
It is moved right by the number of bits specified by the right operand and shifted values are filled
up with zeros.
Example: A >>>2 will give 15 which is 0000 1111

The Logical Operators:


Logical AND operator: && (logical and)
If both the operands are non-zero, then the condition becomes true.
Example (A && B) is false. (0 && 1) or (1 && 0) or (0 && 0) is false & (1 && 1) is true
Logical OR Operator: || (logical or)
If any of the two operands are non-zero, then the condition becomes true.
Example (A || B) is true. (0 || 1) or (1 || 0) or (1 || 1) is true & (0 || 0) is false
Logical NOT Operator: ! (logical not)
Use to reverses the logical state of its operand. If a condition is true then Logical NOT operator
will make false.
Example !(A && B) is true.
instanceof Operator: Type comparision operator
This operator is used only for object reference variables. The operator checks whether the object
is of a particular type (class type or interface type). instanceof operator is written as:
( Object reference variable ) instanceof (class/interface type)
public class Test
{
public static void main(String args[])
{
String name = "James";
boolean result = name instanceof String; System.out.println(
result );
}
}
Op: James

Unary operators: + - ++ - - ! sizeof


UNIT-I

Conditional Operator ( ? : )
Conditional operator is also known as the ternary operator. This operator consists of three
operands and is used to evaluate Boolean expressions. The goal of the operator is to decide which
value should be assigned to the variable. The operator is written as:
variable x = (expression)? value if true : value if false
int x = (10>20)? 100 : 200
Operator Precedence:

Expressions:
An expression is a construct made up of variables, operators, and method invocations, which are
constructed according to the syntax of the language that evaluates to a single value.
int a = 0; arr[0] =
100;
System.out.println("Element 1 at index 0: " + arr[0]); int
result = 1 + 2; // result is now 3
Statements
Statements are roughly equivalent to sentences in natural languages. A statement forms a complete
unit of execution. The following types of expressions can be made into a statement by terminating
the expression with a semicolon (;). Ex: System.out.print(A+B);
Type Conversion and Casting:
We can assign a value of one type to a variable of another type. If the two types are compatible,
then Java will perform the conversion automatically. For example, it is always possible to assign an
int value to a long variable. However, not all types are compatible, and thus, not all type conversions
are implicitly allowed. For instance, there is no conversion defined from double to byte.
But it is possible for conversion between incompatible types. To do so, you must use a cast,
which performs an explicit conversion between incompatible types.
Java„s Automatic Conversions
When one type of data is assigned to another type of variable, an automatic type conversion will take
place if the following two conditions are satisfied:
• The two types are compatible.
• The destination type is larger than the source type.
UNIT-I

When these two conditions are met, a widening conversion (Small data type to Big data type) takes
place. For example, the int type is always large enough to hold all valid byte values, so no explicit
cast statement is required.
For widening conversions, the numeric types, including integer and floating-point types, are
compatible with each other. However, the numeric types are not compatible with char or
boolean. Also, char and boolean are not compatible with each other.
Java also performs an automatic type conversion when storing a literal integer constant into variables
of type byte, short, or long.
Casting Incompatible Types
The automatic type conversions are helpful, they will not fulfill all needs. For example, if we want
to assign an int value to a byte variable. This conversion will not be performed automatically,
because a byte is smaller than an int. This kind of conversion is sometimes called a narrowing
conversion, since you are explicitly making the value narrower so that it will fit into the target type.
To create a conversion between two incompatible types, you must use a cast. A cast is simply an
explicit type conversion.
It has this general form:
(target-type) value
Here, target-type specifies the desired type to convert the specified value to.
Example:
int a; byte
b;
b = (byte) a;
A different type of conversion will occur when a floating-point value is assigned to an integer type:
truncation. As integers do not have fractional components so, when a floating-point value is
assigned to an integer type, the fractional component is lost.
Example Program: Conversion.java
class Conversion {
public static void main(String args[]) {
byte b;
int i = 257;
double d = 323.142; System.out.println("\nConversion of
int to byte."); b = (byte) i;
System.out.println("i and b " + i + " " + b);
System.out.println("\nConversion of double to int."); i =
(int) d;
System.out.println("d and i " + d + " " + i);
System.out.println("\nConversion of double to byte."); b =
(byte) d;
System.out.println("d and b " + d + " " + b);
}
}
UNIT-I

The Type Promotion Rules


Java defines several type promotion rules that apply to expressions. They are as follows:
First, all byte, short, and char values are promoted to int, as just described. Then, if one operand is a
long, the whole expression is promoted to long. If one operand is a float, the entire expression is
promoted to float. If any of the operands is double, the result is double.
Ex:
class Promote { double d = .1234;
public static void main(String args[]) { double result = (f * b) + (i / c) - (d * s);
byte b = 42; System.out.println((f * b) + " + " + (i / c) + "
char c = 'a'; short s - " + (d * s)); System.out.println("result =
= 1024; int i = " + result);
50000; float f = }
5.67f; }

Let‟s look closely at the type promotions that occur in this line from the program:
double result = (f * b) + (i / c) - (d * s);
In the first subexpression, f * b, b is promoted to a float and the result of the subexpression is float.
Next, in the subexpression i/c, c is promoted to int, and the result is of type int. Then, in d*s, the
value of s is promoted to double, and the type of the sub expression is double.
Control Statements or Control Flow:
IF Statement
The IF statement is Java‗s conditional branch statement. It can be used to route program execution
through two different paths.
The general form of the if statement:
if (condition) statement1;
Here, each statement may be a single statement or a compound statement enclosed in curly braces
(that is, a block). The condition is any expression that returns a Boolean value. If the condition is
true, then statement1 is executed.
IF –ELSE Statement
If the condition is true, then statement1 is executed. Otherwise statement2 is executed.
The general form of the if statement:
if (condition) statement1;
else statement2;
The if-then-else statement provides a secondary path of execution when an "if" clause evaluates to
false.
void ifClause()
{
int a, b; if(a
< b) a = 0;
else
b = 0;
}
UNIT-I

Nested ifs
A nested if is an if statement that is the target of another if or else. Here is an example: if(i
== 10)
{
if(j < 20) a =
b;
if(k > 100)
c = d; // this if is
else
a = c; // associated with this else
}
else a = d; // this else refers to if(i == 10)

The if-else-if Ladder


A common programming construct that is based upon a sequence of nested ifs is the if-else-if ladder.
It looks like this:
if(condition) statement;
else if(condition)
statement;
else if(condition)
statement;
else statement;
Example: // Demonstrate if-else-if statements.
class IfElse
{
public static void main(String args[])
{
int month = 4; // April String
season;
if(month == 12 || month == 1 || month == 2) season =
"Winter";
else if(month == 3 || month == 4 || month == 5) season =
"Spring";
else if(month == 6 || month == 7 || month == 8) season =
"Summer";
else if(month == 9 || month == 10 || month == 11)
season = "Autumn";
else
season = "Bogus Month"; System.out.println("April is in
the " + season + ".");
}
}
Output:
April is in the Spring.
UNIT-I

The switch Statement


Unlike if-then and if-then-else, the switch statement allows for any number of possible execution
paths. A switch works with the byte, short, char, and int primitive data types. It also works with
enumerated types.
Program: displays the name of the month, based on the value of month, using the switch
statement.
class SwitchDemo
{
public static void main(String[] args) { int
month = 8;
switch (month) {
case 1: System.out.println("January"); break; case 9: System.out.println("September"); break;
case 2: System.out.println("February"); case 10: System.out.println("October"); break;
break; case 11: System.out.println("November"); break;
case 3: System.out.println("March"); break; case 12: System.out.println("December"); break;
case 4: System.out.println("April"); break; default: System.out.println("Invalid
case 5: System.out.println("May"); break; month.");
case 6: System.out.println("June"); break; break;
case 7: System.out.println("July"); break; }
case 8: System.out.println("August"); break; }
}
Iteration Statements
Output:"August"
Java‗s iteration statements are for, while, and do-while. These statements create what we commonly
call loops. As you probably know, a loop repeatedly executes the same set of instructions until a
termination condition is met.
The while Statement
The while statement continually executes a block of statements while a particular condition is true.
Its syntax can be expressed as:
while (expression)
{
Statements // body of loop
}
Note: The while statement evaluates an expression, which must return a Boolean value.
UNIT-I

Ex: class WhileDemo


{
public static void main(String[] args)
{
int count = 1; while
(count < 11)
{
System.out.println("Count is: " + count); count++;
}
}
}
Output: Count is:1 Count is:2 ....................... Count is:10
do-while statement
The do-while loop always executes its body at least once, because its conditional expression is at the
bottom of the loop. Its syntax can be expressed as:
do
{
statement(s)
} while (expression);
The difference between do-while and while is that do-while evaluates its expression at the bottom of
the loop instead of the top. Therefore, the statements within the do block are always executed at least
once and while terminates with semicolon.
Ex Program:
class DoWhileDemo
{
public static void main(String[] args){ int
count = 1;
do {
System.out.println("Count is: " + count); count++;
} while (count < 11);
}
}
Output: Count is:1 Count is:2 ....................... Count is:10
The for Statement
The for statement provides a compact way to iterate over a range of values. Programmers often refer
to it as the "for loop" because of the way in which it repeatedly loops until a particular condition is
satisfied.
The general form of the for statement can be expressed as follows: for
(initialization; termination; increment) {
statement(s)
}
UNIT-I

Ex: class ForTick {


public static void main(String args[]) { for(int
n=10; n>0; n--)
System.out.println("tick " + n);
}
}

When using the for statement, we need to remember that


• The initialization expression initializes the loop; it's executed once, as the loop begins.
• When the termination expression evaluates to false, the loop terminates.
• The increment expression is invoked after each iteration through the loop; it is perfectly
acceptable for this expression to increment or decrement a value.
// Without using the comma. // Using the comma.
class Sample { class Comma {
public static void main(String args[]) { int public static void main(String args[]) { int a,
a, b; b;
b = 4; for(a=1, b=4; a<b; a++, b--) {
for(a=1; a<b; a++) { System.out.println("a = " + a);
System.out.println("a = " + a); System.out.println("b = " + b);
System.out.println("b = " + b); b--; }
} }
}} }
Output:
Output:
a=1
a=1
b=4
b=4
a=2
a=2
b=3
b=3
For-Each Version of the for Loop
A for-each style loop is designed to cycle through a collection of objects, such as an array, in strictly
sequential fashion, from start to finish. A for-each loop by using the keyword foreach,
Java adds the for-each capability by enhancing the for statement. The advantage of this approach is
that no new keyword is required, and no pre existing code is broken. The for-each style of for is also
referred to as the enhanced for loop.
The general form of the for-each version of the for is shown here:
for(type itr-var : collection) statement-block

//Using for loop //Using for-each loop

int nums[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; int nums[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };


int sum = 0; int sum = 0;
for(int i=0; i < 10; i++) sum += nums[i]; for(int x: nums) sum += x;
UNIT-I

// Use a for-each style for on a 1D array. // Use for-each style for on a 2D array
class ForEach { class ForEach3 {
public static void main(String args[]) { public static void main(String args[]) { int
int nums[ ] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; sum = 0;
int sum = 0; int nums[ ][ ] = new int[3][5];
// use for-each style for to display and sum the // give nums some values
values for(int i = 0; i < 3; i++)
for(int x : nums) { for(int j=0; j < 5; j++)
System.out.println("Value is: " + x); sum nums[i][j] = (i+1)*(j+1);
+= x; // use for-each to display & sum the values
} for(int x[ ] : nums) {
System.out.println("Summation: " + sum); for(int y : x) { System.out.println("Value
} is: " + y); sum += y;
} }}
Output: System.out.println("Summation: " + sum);
Value is: 1 }}
Value is: 2 Output:
Value is: 3 Value is: 1 Value is: 2 Value is: 3
Value is: 4 Value is: 4 Value is: 5
Value is: 5
Value is: 2 Value is: 4 Value is: 6
Value is: 6
Value is: 8 Value is: 10
Value is: 7
Value is: 8 Value is: 3 Value is: 6 Value is: 9
Value is: 9 Value is: 12 Value is: 15
Value is: 10 Summation: 90
Summation: 55

Nested Loops
One loop may be inside another.
Ex: Nested.java
class Nested
{
public static void main(String args[])
{ Output:
int i, j; .........
for(i=1; i<10; i++) ........
{ .......
for(j=i; j<10; j++) ......
{ .....
System.out.print("."); ....
} ...
System.out.println(); ..
} .
}
}
UNIT-I

Unconditional Control Statements


Java supports the following types of unconditional control statements.
1. break:
it is used to break any loop control statement or any switch control statement.
// Using break to exit a loop.
class BreakLoop {
public static void main(String args[]) { for(int
i=0; i<100; i++) {
if(i == 10) break; // terminate loop if i is 10
System.out.print(i+" "); } System.out.print("
Loop complete.");
}}
Output: 0 1 2 3 4 5 6 7 8 9 Loop complete.
2. continue
it is used to skip the current iteration.
// Using continue to skip the current iteration
class BreakLoop {
public static void main(String args[]) { for(int
i=0; i<10; i++) {
if(i == 5) continue;
System.out.print(i+" ");
}
System.out.print(" Loop complete.");
}}
Output: 0 1 2 3 4 6 7 8 9 Loop complete.
3. goto:
The main drawback of goto statement in the c language is it decrease the readability of a program
to avoid that drawback. The goto in java is changed as goto break.
The syntax for the goto statement in java is:
Label:
{
Statements;
Break Label;
}
Example:
// Using break as a civilized form of goto. class
Break {
public static void main(String args[]) { boolean t =
true;
first:
{
second:
{
third:
{
UNIT-I

System.out.println("Before the break.");


if(t) break second; // break out of second block
System.out.println("This won't execute");
}
System.out.println("This won't execute");
}
System.out.println("This is after second block.");
}
}}
Output:
Before the break.
This is after second block.
4. return:
The return control statement is used to jump the control from the called function to the calling function.
Classes and Objects:
A class is a group of objects which have common properties. It is a template or blueprint from which
objects are created. It is a logical entity. A class in Java can contain:
o fields
o methods
o constructors
o blocks
o nested class and interface
Declaring Member Variables
There are several kinds of variables:
• Member variables in a class—these are called fields.
• Variables in a method or block of code—these are called local variables.
• Variables in method declarations—these are called parameters.
Syntax to declare a class:
class <class_name>{ field;
method;
}
A class is declared by use of the class keyword
class classname type methodname2(parameter-list)
{ {
type instance-variable1; // body of method
type instance-variable2; }
// ... // ...
type instance-variableN; type methodnameN(parameter-list)
type methodname1(parameter-list) {
{ // body of method
// body of method }
} }
UNIT-I

The data, or variables, defined within a Example:


class are called instance variables. The Class demo {
code is contained within methods. int x=1;;
Collectively, the methods and variables int y=2;
defined within a class are called float z=3;
members of the class. Variables void display()
defined within a class are called {
instance variables. System.out.println(―values are:‖+x+--y+--z);
}
}
OBJECTS:
An entity that has state and behavior is known as an object e.g. chair, bike, marker, pen, table, car
etc. It can be physical or logical (tangible and intangible). The example of intangible object is
banking system.
An object has three characteristics:
o state: represents data (value) of an object.
o behavior: represents the behavior (functionality) of an object such as deposit, withdraw etc.
o identity: Object identity is typically implemented via a unique ID. The value of the ID is not
visible to the external user. But, it is used internally by the JVM to identify each object
uniquely.
For Example: Pen is an object. Its name is Reynolds, color is white etc. known as its state. It is used
to write, so writing is its behavior.
Object is an instance of a class. Class is a template or blueprint from which objects are created. So
object is the instance(result) of a class.
Object Definitions:
o Object is a real world entity.
o Object is a run time entity.
o Object is an entity which has state and behavior.
o Object is an instance of a class.

New keyword in Java


The new keyword is used to allocate memory at run time. All objects get memory in Heap memory
area.
Declaring Objects
When you create a class, you are creating a new data type. You can use this type to declare objects
of that type. However, obtaining objects of a class is a two-step process.
First, you must declare a variable of the class type. This variable does not define an object. Instead, it
is simply a variable that can refer to an object.
Second, you must acquire an actual, physical copy of the object and assign it to that variable. You
can do this using the new operator.
Demo d1 = new demo( );
UNIT-I

Object and Class Example: main within class


In this example, we have created a Student class that has two data members id and name. We are creating
the object of the Student class by new keyword and printing the objects value.
Here, we are creating main() method inside the class.
Student.java
class Student
{
int id;//field or data member or instance variable String
name;
public static void main(String args[])
{
Student s1=new Student();//creating an object of Student
System.out.println(s1.id);//accessing member through reference variable
System.out.println(s1.name);
}
}
Output:
0
null
Object and Class Example: main outside class
If you define multiple classes in a single java source file, it is a good idea to save the file name with
the class name which has main() method.
TestStudent1.java
class Student
{
int id;
String name;
}
class TestStudent1{
public static void main(String args[])
{
Student s1=new Student();
System.out.println(s1.id);
System.out.println(s1.name);
}
}
Output:
0
null
UNIT-I
Arrays:
An array is a group of similar-typed variables that are referred to by a common name. Arrays of any
type can be created and may have one or more dimensions. A specific element in an array is
accessed by its index. Arrays offer a convenient means of grouping related information.
One-Dimensional Arrays
A one-dimensional array is a list of like-typed variables. To create an array, you first must create an
array variable of the desired type. The general form of a one dimensional array declaration is type
var-name[ ]; Here, type declares the base type of the array.
int month [ ];
Although this declaration establishes the fact that month is an array variable, no array actually exists.
In fact, the value of month is set to null, which represents an array with no value.
To link month with an actual, physical array of integers, you must allocate one using new and assign
it to month. new is a special operator that allocates memory.
The general form of new as it applies to one-dimensional arrays appears as follows:
array-var = new type[size];

Ex: month = new int[12];


After this statement executes, month will refer to an array of 12 integers. Further, all elements in the
array will be initialized to zero.
Another way to declare an array in single step is
type arr-name=new type[size];
Ex: int month = new int[12];
Arrays can be initialized when they are declared. For example, to store the number of days in each
month, we do as follows
Example Program1: // An improved version of the previous program. class
AutoArray
{
public static void main(String args[])
{
int month[ ] = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31,30, 31 };
System.out.println("April has " + month[3] + " days.");
}
}
When you run this program, in the output it prints the number of days in April. As mentioned, Java
array indexes start with zero, so the number of days in April has 30 days.
UNIT-I

Example Program2: // Average an array of values. class


Average
{
public static void main(String args[])
{
double nums[] = {10.1, 11.2, 12.3, 13.4, 14.5};
double result = 0; int i;
for(i=0; i<5; i++)
result = result + nums[i];
System.out.println("Average is " + result / 5);
}
}
Output: Average is:12.3
Multidimensional Arrays
In Java, multidimensional arrays are actually arrays of arrays. To declare a multidimensional array
variable, specify each additional index using another set of square brackets. For example, the
following declares a two-dimensional array variable called twoD.
int twoD[ ][ ] = new int[4][5];
Example Program: Example Program:
// Demonstrate a two-dimensional array //Demonstrate a three-dimensional array.
class Testarray1 class threeDMatrix
{ {
public static void main(String args[]) public static void main(String args[])
{ {
int threeD[][][] = new int[3][4][5]; int i, j,
//declaring and initializing 2D array int
k;
arr[][]={{1,2,3},{4,5,6},{7,8,9}};
for(i=0; i<3; i++) for(j=0; j<4;
//printing 2D array for(int j++) for(k=0; k<5; k++)
i=0;i<3;i++) threeD[i][j][k] = i * j * k;
{
for(int j=0;j<3;j++) for(i=0; i<2; i++)
{ {
System.out.print(arr[i][j]+" "); for(j=0; j<2; j++)
} {
System.out.println(); for(k=0; k<3; k++)
} System.out.print(threeD[i][j][k] + " ");
} System.out.println();
} }
System.out.println();
Output: }}}
1 23 Output:
4 56 000 000
7 89 000 012
UNIT-I

We can create a three-dimensional array where first index specifies the number of tables, second
one number o0f rows and the third number of columns.
Alternative Array Declaration Syntax
There is a second form that may be used to declare an array:
type[ ] var-name;
For example, the following two declarations are equivalent: int al[ ]
= new int[3];
int[ ] a2 = new int[3];
Constructors:
Constructor is a special method of a class which is invoked automatically whenever an object is
created. It has same name that of a class. A constructor initializes an object immediately upon
creation. A constructor has no return type; not even void. It cannot be abstract, final, native
,static or synchronized. this keyword refers another constructor in same class. A super keyword
will call constructor of super class constructors are of two type
1.Default constructor
2.Parameterised constructor
1. Default constructor:
A constructor that accepts no parameters is called default constructor. If no constructor is defined for
a class java system automatically generates the default constructor. A default constructor is called
when an instance is created for a class. The default constructor automatically initializes all
instance variables to zero.
Example:
class demo
{
int x,y;
float z;
demo()
{ x=1;
y=2; z=3;
}
void display()
{
System.out.println("Values of x, y and z are:"+x+" "+y+" "+z);
}
}
class Demomain
{
public static void main(String args[])
{
demo d1=new demo( ); // this is a call for the above default constructor d1.display();
}
}
Output: Values of x,y and z are: 1 2 3.0
UNIT-I

Parameterized constructor: A constructor that takes arguments as parameters is called as


parameterized constructor
class demo System.out.println("Values of x, y and z are:"+x+"
{ "+y+" "+z);
int x; int }
y; float z; }
demo(int x1,int y1,int z1) class Demomain1
{ {
x=x1; public static void main(String args[])
y=y1; {
z=z1; demo d1=new demo(1,2,3); // this is a call for
} the above parameterized constructor
void display() d1.display();
{ }
}Output: Values of x,y and z are: 1 2 3.0
Java Copy Constructor
There is no copy constructor in java. But, we can copy the values of one object to another like copy
constructor in C++. There are many ways to copy the values of one object into another in java. They
are:
 By constructor
 By assigning the values of one object into another
 By clone() method of Object class

In this example, we are going to copy the values of one object into another using java
constructor.
Example:
class Student6{ {
int id; String name; System.out.println(id+" "+name); }
Student6(int i,String n){ id = i; public static void main(String args[])
name = n; {
} Student6 s1 = new Student6(111,"Karan"); Student6 s2
Student6(Student6 s){ id = = new Student6(s1);
s.id; s1.display();
name =s.name; s2.display();
} }}
void display() Output: 111 Karan
111 Karan

Methods:
Method is an action required by an object. Methods allow the programmer to modularize the
program. All variables declared in method definitions are local variables. That means they are
known only in the method in which they are defined. Most methods have a list of parameters that
provide the means for communicating information between the methods. A methods parameters are
also local variables.

static : (constant / fixed)


It can be applied to data members, methods and some inner classes.
static data members :
UNIT-I
1. static data members can be accessed by only static methods as well as non static.
2. They can be accessed directly with the class name. E.g., classname.variable_name;
3. For all objects of a class, only one copy of static members exists in memory and it is
shared by all objects. It is contrary to instance variables.
4. static variables are declared as static int x ;
static methods :
1. static method is a method whose definition is preceded by keyword static.
2. static methods can act upon only static variables.
3. static method can be called directly using class name without creating object.
4. The keyword “this” can‟ t be used inside a static method, as static members don‗ t belongs
to any particular object.
5. A static method can call only other static methods .
static block:
1. It is a piece of code enclosed in braces preceded by the keyword static.
2. static block is executed even before main() .
3. It is used to initialize some variables or any such things.
4. It can use only static variables & call only static methods.
Sno Constructor Method
1 Creates an instance of a class Group of statements
2 Cannot be abstract ,final,static,native or Can be final , abstract,static, native or
synchronized synchronized
3 NO return type not even void Will have all possible return types
including void
4 Has same that of a class Can be given any valid name
5 this keyword Refers another constructor this keyword refers to an instance of the
in the same class. class . cannot be used with static methods
6 Super keyword is used ot call constructor super calls the super class overridden
of super class method
7 By default no arguments are supplied to No default supply of arguments
constructor

Sno Instance method Static method


1 Instance methods perform an operation Static methods perform an operation for
on individual objects of a class entire class
2 Instance methods uses instance variable Static method do not use instance variable
of that object of object of the class
3 Instance method in invoked by an object Static method in invoked by Class name
variable followed by dot operator followed followed by dot operator followed by
by method name method name
4 Instance method cannot be invoked unless Static methods can be invoked without
an instance of the class has already creating an instance of the class
created
UNIT-I

Access Specifiers:
There are 4 types of java access modifiers: private, public, protected and default
Access Specifiers are the keywords that alter the meaning and accessibility (scope) of a data
member of a class, method or constructor. They are, private, public, protected and default. There
are many non-access modifiers such as static, final, abstract, native, synchronized, transient and
volatile.
private:
It can be applied to variables and methods. Private members of a class are accessible from within
the class only. They cannot be accessed from outside the class and its subclass.
Ex: class A
{
private int data=40;
private void msg(){System.out.println("Hello java");}
}
public class Simple
{
public static void main(String args[])
{
A obj=new A(); System.out.println(obj.data);//Compile
Time Error obj.msg();//Compile Time Error
}
}
Output: compile time error
Role of Private Constructor: If you make any class constructor private, you cannot create the
instance of that class from outside the class.
Ex: class A{
private A(){}//private constructor
void msg(){System.out.println("Hello java");}
}
public class Simple{
public static void main(String args[]){ A
obj=new A();//Compile Time Error
} } Output: compile time error
Note: A class cannot be private or protected except nested class.
public:
It can be applied to variables (data members), methods and classes. Public member of class can be
accessed globally any other code. They can be accessed from outside the class and sub class. A
public class can be accessed from any package.
class Alpha
{
public int i;
UNIT-I

public void publicMethod()


{
System.out.println("in PublicMethod");
System.out.println("i="+i);
}
}
class Beta
{
public static void main(String args[])
{
Alpha a=new Alpha(); a.i=10;
a.publicMethod();
}
}
Output:
in PublicMethod
i=10
protected:
It can be applied to data members and methods. Protected member of a class can be accessed from
within the class, sub class in the same package and sub class in different package. It cannot be
accessed from a non-subclass in different package.
default: When no access specifier is mentioned for a data member, method or class. It assumes
default / friend. There are no keywords such as default or friend. The default / friend members of a
class can be accessed from anywhere except from sub class in different package and non-sub class
from different package. (Ex: Public access specifier program without public)

Variable Method Class within within outside package by outside


class package subclass only package

private Y Y N Y N N N
public Y Y Y Y Y Y Y
protected Y Y N Y Y Y N
default Y Y Y Y Y N N
static Y Y Y - - - -
final Y Y Y - - - -
this Keyword:
Sometimes a method will need to refer to the object that invoked it. To allow this, Java defines the
this keyword. this can be used inside any method to refer to the current object. That is, this is
always a reference to the object on which the method was invoked.
UNIT-I

private void formatFullName()


{
this.fullName = String.format("%s %s", this.firstName, this.lastName);
}
Example 1:
class demo System.out.println("Values of x, y and z are:"+x+"
{ "+y+" "+z);
int x; int }
y; float z; }
demo(int x,int y,int z) class Demomain2
{ {
this.x=x; public static void main(String args[])
this.y=y; {
this.z=z; demo d1=new demo(1,2,3); // this is a call for
} the above parameterized constructor
void display() d1.display();
{ }}
Output: Values of x, y and z are:1 2 3.0
Example 2:
class ThisRef
{ public static void main(String args[])
int age=40; {
ThisRef(int age) ThisRef s=new ThisRef(20);
{ System.out.print(s.age);
this.age = age; System.out.println(age); }
} }
Op: 20
20 //without using this keyword 40
To differentiate between the local and instance variables we have used this keyword in the
constructor.
Garbage Collection
Garbage Collection is process of reclaiming the runtime unused memory automatically. In other
words, it is a way to destroy the unused objects. To do so, we were using free() function in C
language and delete() in C++. But, in java it is performed automatically. So, java provides better
memory management.
Advantage of Garbage Collection
oIt makes java memory efficient because garbage collector removes the unreferenced objects from
heap memory.
o It is automatically done by the garbage collector(a part of JVM).
UNIT-I
Method Overloading in Java
If a class has multiple methods by same name but different 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 we 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
behaviour of the method because its name differs.

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 this example, we have created two In this example, we have created two
overloaded methods, first sum method overloaded methods that differ in data type.
performs addition of two numbers and The first sum method receives two integer
second sum method performs addition of arguments and second sum method receives
three numbers. two double arguments.
class Calculation{ class Calculation2
void sum(int a,int b){ System.out.println(a+b);} {
void sum(int a,int b,int c){ void sum(int a,int b)
System.out.println(a+b+c);} {System.out.println(a+b);}
public static void main(String args[]){ void sum(double a,double b)
Calculation obj=new Calculation(); {System.out.println(a+b); }
obj.sum(10,10,10); public static void main(String args[]){
obj.sum(20,20); Calculation2 obj=new Calculation2();
} obj.sum(10.5,10.5);
} Output: 30 obj.sum(20,20);
40 } } Output: 21.0
40

Constructor Overloading in Java


Constructor overloading is a technique in Java in which a class can have any number of constructors
that differ in parameter lists. The compiler differentiates these constructors by taking into account
the number of parameters in the list and their type.
UNIT-I
Example of Constructor Overloading
class Student5{ {
int id; String System.out.println(id+" "+name+" "+age);
name; int age; }
Student5(int i,String n){ id = i; public static void main(String args[ ])
name = n; {
} Student5 s1 = new Student5(11,"IF");
Student5(int i,String n,int a){ id = i; Student5 s2 = new Student5(22,"CSE",25);
name = n; age=a; s1.display( );
} s2.display( );
void display( ) }
}
Output:
Recursion: 11 IF 0
22 CSE 25
Java supports recursion. Recursion is the process of defining something in terms of itself. As it
relates to Java programming, recursion is the attribute that allows a method to call itself.
A method that calls itself is said to be recursive.
Example: Write a program to display Fibonacci // recursive declaration of method
series without using Recursion. fibonacci
public class Fib public class MainClass1 {
{ public static long fib(long no)
public static void main(String args[]){ String n1; {
int f1=0,f2=1,n,i,f3; if ((no == 0) || (no == 1)) return no;
n1="5"; else
n=Integer.parseInt(n1); // recursion step
System.out.println("Series\n"+f1+"\n"+f2); return fib(no - 1) + fib(no - 2);
for(i=1;i<n;i++) }
{ public static void main(String[] args)
f3=f1+f2; {
System.out.println(f3); f1=f2; System.out.printf("Fibonacci of 10:\n");
f2=f3; for (int coun = 0; coun < 10; coun++)
} System.out.printf("%d\t", fib(coun));
} }
} }
Output: Series: 0 1 1 2 3 5 Output: Fibonacci of 10:
0 1 1 2 3 5 8 13 21 34
UNIT-I

Example: Factorial of a number using Recursion.


The factorial of a number N is the product of all the whole numbers between 1 and N. For example, 3
factorial is 1 × 2 × 3, or 6.
class Factorial { Factorial f = new Factorial();
int fact(int n) { // this is a recursive method System.out.println("Fact of 3 is " + f.fact(3));
int result; System.out.println("Fact of 4 is " + f.fact(4));
if(n==1) return 1; System.out.println("Fact of 5 is " + f.fact(5));
result = fact(n-1) * n; }
return result; }
} Output:
} Factorial of 3 is 6
class Recursion { Factorial of 4 is 24
public static void main(String args[]) { Factorial of 5 is 120
BufferedReader class (or) Console Input and Output:
In Java, console input is accomplished by reading from System.in or reading data from keyboard.
To obtain a character-based stream that is attached to the console, wrap System.in in a
BufferedReader object. BufferedReader supports a buffered input stream. Reader is an abstract
class. One of its concrete subclasses is InputStreamReader, which converts bytes to characters.
To obtain an InputStreamReader object that is linked to System.in, the following line of code creates a
BufferedReader that is connected to the keyboard:
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
After this statement executes, br is a character-based stream that is linked to the console through
System.in.

Reading Characters
To read a character from a BufferedReader, use read( ). The version of read( ) that we will be using
is int read( ) throws IOException. Each time that read( ) is called, it reads a character from the
input stream and returns it as an integer value. It returns – 1 when the end of the stream is
encountered. As you can see, it can throw an IOException.
Example Program: // Use a BufferedReader to read characters from the console.
import java.io.*;
class BRRead {
public static void main(String args[]) throws IOException
{
char c;
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter characters, 'q' to quit.");
do { // read characters
c = (char) br.read(); System.out.println(c);
} while(c != 'q');
}
}
UNIT-I
Reading Strings
To read a string from the keyboard, use the version of readLine( ) that is a member of the
BufferedReader class. Its general form is shown here:
String readLine( ) throws IOException
The following program demonstrates BufferedReader and the readLine() method; The
program reads and displays lines of text until you enter the word ―stop‖:
Example Program: // Read a string from console using a BufferedReader
import java.io.*; class
BRReadLines {
public static void main(String args[]) throws
IOException
{
// create a BufferedReader using System.in
BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); String
str;
System.out.println("Enter lines of text.");
System.out.println("Enter 'stop' to quit."); do
{
str = br.readLine();
System.out.println(str);
} while(!str.equals("stop"));
}
}
Java Scanner class
There are various ways to read input from the keyboard, the java.util.Scanner class is one of
them. The Java Scanner class breaks the input into tokens using a delimiter that is whitespace
bydefault. It provides many methods to read and parse various primitive values.
Java Scanner class is widely used to parse text for string and primitive types using regular expression.
Java Scanner class extends Object class and implements Iterator and Closeable interfaces.
There is a list of commonly used Scanner class methods:
Method Description
public String next() it returns the next token from the scanner.
public String nextLine() it moves the scanner position to the next line and returns the value as
a string.
public byte nextByte() it scans the next token as a byte.
public short nextShort() it scans the next token as a short value.
public int nextInt() it scans the next token as an int value.
public double nextDouble() it scans the next token as a double value.
public float nextDouble() it scans the next token as a float value.
UNIT-I

Java Scanner Example to get input from console


Simple example of the Java Scanner class which reads the int, string & double value as an input:
import java.util.Scanner; String name=sc.next();
class ScannerTest System.out.println("Enter your fee");
{ double fee=sc.nextDouble();
public static void main(String args[]) System.out.println("Rollno:"+rollno+
{ " name:"+name+" fee:"+fee); sc.close();
Scanner sc=new Scanner(System.in); }
System.out.println("Enter your rollno"); int }
rollno=sc.nextInt(); System.out.println("Enter
your name");
Output:
Enter your rollno
111
Enter your name
Kalpana
Enter
450000
Rollno:111 name:Kalpana fee:450000
Strings:
Java String provides a lot of concepts that can be performed on a string such as compare, concat,
equals, split, length, replace, compareTo, intern, substring etc.
In java, string is basically an object that represents sequence of char values. An array of characters
works same as java string. For example:
char[] ch={'j','a','v','a' };
String s=new String(ch);
Above code is same as: String s="java";
The java String is immutable i.e. it cannot be changed but a new instance is created. For
mutable class, you can use StringBuffer and StringBuilder class.
What is String in java
Generally, string is a sequence of characters. But in java, string is an object that represents a
sequence of characters. String class is used to create string object.
There are two ways to create String object:
1. By string literal
2. By new keyword
1) String Literal
Java String literal is created by using double quotes.
For Example:
String s="welcome";
UNIT-I

Each time you create a string literal, the JVM checks the string constant pool first. If the string
already exists in the pool, a reference to the pooled instance is returned. If string doesn't exist in
the pool, a new string instance is created and placed in the pool. For example:
String s1="Welcome";
String s2="Welcome"; //will not create new instance
In the beside example only one object will
be created. Firstly JVM will not find any
string object with the value "Welcome" in
string constant pool, so it will create a new
object. After that it will find the string
with the value "Welcome" in the pool, it
will not create new object but will return
the reference to the same instance.

Note: String objects are stored in a special memory area known as string constant pool.
Java has more memory efficient, because no new objects are created if it exists already in string constant
pool.
2) By new keyword
String s=new String("Welcome"); //creates two objects and one reference variable
Java String Example
public class StringExample{
public static void main(String args[]){
String s1="java";//creating string by java string literal char
ch[]={'s','t','r','i','n','g','s'};
String s2=new String(ch); //converting char array to string
String s3=new String("example"); //creating java string by new keyword System.out.println(s1);
System.out.println(s2);
System.out.println(s3);
}}
Difference between StringBuffer and StringBuilder
There are many differences between StringBuffer and StringBuilder. A list of differences between
StringBuffer and StringBuilder are given below:
No. StringBuffer StringBuilder
1) StringBuffer is synchronized i.e. StringBuilder is non-synchronized i.e. not
thread safe. It means two threads can't thread safe. It means two threads can call the
call the methods of StringBuffer methods of StringBuilder simultaneously.
simultaneously.
2) StringBuffer is less efficient than StringBuilder is more efficient than
StringBuilder. StringBuffer.
UNIT-I

StringBuffer Example StringBuilder Example


public class BufferTest{ public class BuilderTest{
public static void main(String[] args) { public static void main(String[] args) {
StringBuffer buffer=new StringBuffer("hello"); StringBuilder builder=new StringBuilder("hello");
buffer.append("java"); builder.append("java");
System.out.println(buffer); System.out.println(builder);
} }
} }
OP: hellojava OP: hellojava
Immutable String in Java
In java, string objects are immutable. Immutable simply means unmodifiable or
unchangeable. Let's try to understand the immutability concept by the example given below:
class Testimmutablestring{
public static void main(String args[]){ String
s="Sachin";
s.concat(" Tendulkar"); //concat() method appends the string at the end
System.out.println(s); //will print Sachin because strings are immutable objects
} }
Output: Sachin
String Handling Methods:
String compare by compareTo( ) method
The String compareTo() method compares values lexicographically and returns an integer value that
describes if first string is less than, equal to or greater than second string.
Suppose s1 and s2 are two string variables. If:
s1 == s2 :0 s1 > s2 :positive value s1 < s2 :negative value
String compare by == operator String compare by compareTo method
The = = operator compares references not values.
class Teststringcomparison4
class Teststringcomparison3 {
{ public static void main(String args[])
public static void main(String args[ ]) {
{ String s1=" kalpana";
String s1="Sachin"; String s2=" kalpana";
String s2="Sachin"; String s3="Chavla";
String s3=new String("Sachin"); System.out.println(s1.compareTo(s2));//0
System.out.println(s1==s2);//true (because System.out.println(s1.compareTo(s3));
both refer to same instance) //1(because s1>s3)
System.out.println(s1==s3);//false(because s System.out.println(s3.compareTo(s1));
3 refers to instance created in nonpool) //-1(because s3 < s1 )
} System.out.println(s1.equals(s2));//true
} }
Output: true }
false Output: 0 1 -1 true
UNIT-I

String Concatenation by + (string concatenation) operator


In java, string concatenation forms a new string that is the combination of multiple strings. There are
two ways to concat string in java:
1. By + (string concatenation) operator
2. By concat() method
Java string concatenation operator (+) is used to add strings. For Example: class
TestStringConcatenation1{
public static void main(String args[]){ String
s="Adv"+" Java"; System.out.println(s); //
AdvJava
}
}
For example concat():
class Testimmutablestring1{
public static void main(String args[]){ String
s="Adv";
s=s.concat(" Java");
System.out.println(s);
}
}
Output: AdvJava
Substring in Java
A part of string is called substring.
In case of string:
o startIndex: inclusive
o endIndex: exclusive
Let's understand the startIndex and endIndex by the code given below.
String s="hello";
System.out.println(s.substring(0,2));//he
In the above substring, 0 points to h but 2 points to e (because end index is exclusive).
Example of java substring public
class TestSubstring{
public static void main(String args[]){ String
s="Sachin Tendulkar";
System.out.println(s.substring(6));//Tendulkar
System.out.println(s.substring(0,6));//Sachin
}
}
Output:
Tendulkar
Sachin
UNIT-I

Java String toUpperCase() and toLowerCase() method


The java string toUpperCase() method converts this string into uppercase letter and string toLowerCase()
method into lowercase letter.
String s="Kalpana";
System.out.println(s.toUpperCase());//KALPANA
System.out.println(s.toLowerCase());//kalpana
System.out.println(s); // Kalpana (no change in original)
Java String trim() method
The string trim() method eliminates white spaces before and after string.
String s=" Kalpana ";

System.out.println(s); // Kalpana
System.out.println(s.trim()); //Kalpana
Java String startsWith() and endsWith() method
String s="Kalpana";

System.out.println(s.startsWith("Ka")); //true
System.out.println(s.endsWith("a")); //true
Java String charAt() method
The string charAt() method returns a character at specified index.
String s="Sachin";
System.out.println(s.charAt(0));//S
System.out.println(s.charAt(3));//h
Output:
S
h
Java String length() method
The string length() method returns length of the string.
String s="Kalpana ";
System.out.println(s.length());//7
Output:
7
Java String replace() method
The string replace() method replaces all occurrence of first sequence of character with second sequence
of character.
String s1="Java is a programming language. Java supports OOP features.";
String replaceString=s1.replace("Java","CPP"); //replaces all occurrences of "Java" to "CPP"
System.out.println(replaceString);
Output: CPP is a programming language. CPP supports OOP features.
II
UNIT-II
Inheritance
Inheritance can be defined as the process where one class acquires the properties methods and
fields of another. With the use of inheritance the information is made manageable in a hierarchical
order. The class which inherits the properties of other is known as subclass derived class, child
class and the class whose properties are inherited is known as super class base class, parent class.
Inheritance is the mechanism of deriving new class from old one, old class is known as super
class and new class is known as subclass. The subclass inherits all of its instances variables and
methods defined by the super class and it also adds its own unique elements. Thus we can say
that subclass is specialized version of superclass.
Benefits of Java’s Inheritance
1. Reusability of code
2. Code Sharing
3. Consistency in using an interface
Classes
Superclass(Base Class) Subclass(Child Class)
It is a class from which other classes It is a class that inherits some or all
can be derived. members from superclass.

extends Keyword
extends is the keyword used to inherit the properties of a class. Below given is the syntax of extends
keyword.
class Super{
........... } Base Class
class Sub extends Super{
............ } Derived Class

Types of Inheritance in Java


There are various types of inheritance as demonstrated below

Single Level Inheritance:


When one base class is being inherited by one sub class then that kind of inheritance is known as
single level inheritance.
Multi Level Inheritance:
When a sub class is in turn being inherited then that kind of inheritance is known as multi level
inheritance.
Hierarchical Inheritance:
When a base class is being inherited by one or more sub class then that kind of inheritance is known
as hierarchical inheritance.

Multiple inheritance:
Deriving one subclass from more than one super classes is called multiple inheritance.
Eg. class A { statements ; }
class B { statements ; }
class C extends A, B { statements ; }
Note: Java does not support multiple inheritance with classes. But, it supports multiple
inheritance using interfaces.
II
Hybrid Inheritance: It is a combination of multiple and hierarchical inheritance.
A
HIERARCHICAL INHERITANCE MULTIPLE

B C INHERITANCE

D
A sub class uses the keyword “extends” to inherit a base class.

Example for Single Inheritance: System.out.println(b);


class x }}
{ class show_main
int a; {
void display() { public static void main(String args[])
a=0; {
System.out.println(a); y y1=new y(); y1.display();
}} y1.show();
class y extends x { int b; }}
void show( ) Output:
{ 0
B=1; 1
Since the class y is inheriting class x, it is able to access the members of class x. Hence the
method display() can be invoked by the instance of the class y.
II

Example for multilevel inheritance: class z extends y{


class x int c;
{ show1()
int a; {
void display() c=2;
{ System.out.println(c);
a=0; }
System.out.println(a); }
} class show_main
} {
class y extends x public static void main(String args[])
{ {
int b; z z1=new z();
void show() z1.display();
{ z1.show();
B=1; }
System.out.println(b); }
}}

Output:
0
1
2
II
Since class z is inheriting class y which is in turn a sub class of the class x, indirectly z can access the
members of class x. Hence the instance of class z can access the display () method in class x, the
show () method in class y.
Problems:
In java multiple level inheritance is not possible easily. We have to make use of a concept called
interfaces to achieve it.

Super Keyword:
Whenever a sub class needs to refer to its immediate super class, we can use the super keyword.
Super has two general forms
• The first calls the super class constructor.
• The second is used to access a member of the super class that has been hidden by a
member of a sub class
Syntax:
A sub class can call a constructor defined by its super class by use of the following form of
super.
super(arg-list);
here arg-list specifies any arguments needed by the constructor in the super class .
The second form of super acts like a”this” keyword. The difference between ―this‖ and ―super‖ is
that “this” is used to refer the current object where as the super is used to refer to the super
class.
The usage has the following general form:
super.member;
Example:
class x b=1;
{ }
int a; x( ) void display( )
{ {
a=0; super.display( );
} System.out.println(b);
void display( ) }
{ }
System.out.println(a); class super_main
} {
} public static void main(String args[ ])
class y extends x {
{ y y1=new y( ); y1.display(
int b; y( ) );
}
}
{ Output: 0 1
super( );
super is a reference variable that is used to refer immediate parent class object. Uses of super
keyword are as follows:
1. super() is used to invoke immediate parent class constructors
2. super is used to invoke immediate parent class method
3. super is used to refer immediate parent class variable
II

Example:

To print the value of Base class


variable in a child class use
super.variable name

This“i” will print


Value of local class
variable

Output:

Example to call Immediate Parent Class Constructor using super Keyword


The super() keyword can be used to invoke the Parent class constructor as shown in the example
below.

Output:
II
Preventing Inheritance:
Final Keyword: ( last / concluding )
Final keyword can be used in the following ways:
Final Variable: Once a variable is declared as final, its value cannot be changed during
the scope of the program
Final Method: Method declared as final cannot be overridden
Final Class: A final class cannot be inherited
Using final with inheritance:
The keyword final has three uses.
• First it can be used to create the equivalent of a named constant.
• To prevent overriding.
• To prevent inheritance.
final data members:
Data member with final modifier becomes a constant.
Using final to prevent overriding:
To disallow a method from being overridden, specify final as a modifier at the start of the
declaration.
Methods declared as final cannot be overridden.
Syntax: final <return type> <method name> (argument list); final
returntype funname()
{-----
}
Using final to prevent inheritance:
Some times we may want to prevent a class from being inherited. In order to do this we must
precede the class declaration with final keyword.
Declaring a class as final implicitly declares all its methods as final. The final class can’ t be
sub classed or derived. This means that we can‟ t create a sub class from a final class.

Example:
final class A { class B
extends A{
}}

The above code gives compile error. Because class A is a final class, which can‟ t be derived.
Example of Final Variable: Final variables work like const of C-language that can‟t be altered in the
whole program. That is, final variables once created can‟t be changed and they must be used as it is
by all the program code.
II

Variable “i” is declared as final

In this code we are trying to


modify the value of a Final
Variable which will result in error
as shown in the output.

Output:

Example of Final Method:

Generally, a super class method can be overridden by the subclass if it wants a different
functionality. If the super class desires that the subclass should not override its method, it declares
the method as final. ( it gives compilation error).
II

Output

Example of Final Class: If we want the class not be sub-classed(or extended) by any other class,
declare it final. Classes declared final can not be extended.

Difference between method overloading and method overriding in java There are
many differences between method overloading and method overriding in java. A list of differences
between method overloading and method overriding are given below:
No. Method Overloading Method Overriding
1) Method overloading is used to increase Method overriding is used to provide the
the readability of the program. specific implementation of the method that
is already provided by its super class.

2) Method overloading is performed within Method overriding occurs in two classes


class. that have IS-A (inheritance) relationship.

3) In case of method In case of method


overloading, parameter must be different. overriding, parameter must be same.

4) Method overloading is the example of Method overriding is the example


compile time polymorphism. of run time polymorphism.
5) In java, method overloading can't be Return type must be same or
performed by changing return type of the covariant in method overriding.
method only. Return type can be same or
different in method overloading. But you
must have to change the parameter.
II
6) Java Method Overloading example Java Method Overriding example
class OverloadingExample{ class Animal{
static int add(int a,int b){ void eat(){System.out.println("eating...");
return a+b; }
} }
static int add(int a,int b,int c){ class Dog extends Animal{
return a+b+c; void eat(){
}} System.out.println("eating bread...");} }

Abstraction in Java
Abstraction is a process of hiding the implementation details and showing only functionality to
the user. Another way, it shows only important things to the user and hides the internal details for
example sending sms, you just type the text and send the message. You don't know the internal
processing about the message delivery.
Ways to achieve Abstaction
There are two ways to achieve abstraction in java
1. Abstract class (0 to 100%)
2. Interface (100%)
Note1: It can be applied to methods and classes. It cannot be used with data members.
Note2: It needs to be extended and its method implemented. It cannot be instantiated.
Abstract class in Java
A class that is declared with abstract keyword, is known as abstract class in java. It can have
abstract and non-abstract methods (method with body).
Example abstract class
abstract class A{}
1. Abstract class is a class that cannot be instantiated. (no creation of object).
2. It can be / must be inherited.
3. It can act as only base class in inheritance hierarchy. (levels)
Abstract method
A method that is declared as abstract and does not have implementation is known as
abstract method.
1. It is a method, which has no body (definition) in the base class. The body should be
implemented in the sub class only.
2. Any class with at least one abstract method should be declared as abstract.
3. If the sub class is not implementing an abstract method, its sub class has to implement it.
Example abstract method

abstract void printStatus(); //no body and abstract


Example of abstract class that has abstract method
In this example, Bike the abstract class that contains only one abstract method run. It
implementation is provided by the Honda class.
abstract class Parent{ Note: With respect to a class,
abstract void run(); abstract and final are exclusive.
} They both cannot be applied to a
class Child extends Parent{ class of a time.
void run(){System.out.println("Child
abstract final class A
calling..");}
{
public static void main(String args[]){ Parent obj }
= new Child();
(The above code is wrong)
obj.run();
}
}
Output: Child calling..
II
File: TestAbstraction1.java File: TestBank.java
abstract class Shape{ abstract class Bank{
abstract void draw(); abstract int getRateOfInterest();
} }
class Rectangle extends Shape{ class SBI extends Bank{
void draw(){System.out.println("drawing rectangle"); int getRateOfInterest(){return 7;}
} }
} class PNB extends Bank{
class Circle1 extends Shape{ int getRateOfInterest(){return 5;}
void draw(){System.out.println("drawing circle");} }
} class TestBank{
class TestAbstraction1{ public static void main(String
public static void main(String args[]){ args[ ]){
Shape s=new Circle1();//In real scenario, object is pro Bank b=new SBI();
vided through method e.g. getShape() method int interest=b.getRateOfInterest();
s.draw(); System.out.println("Rate of Interest
} is: "+interest+" %");
} }}
Output: drawing circle Output: Rate of Interest is: 7 %
II

Abstract class having constructor, data member, methods etc.


An abstract class can have data member, abstract method, method body, constructor and even main()
method.
File: TestAbstraction2.java
//example of abstract class that have method body
abstract class Bike{ Bike( ){
Rule: If there is any abstract method in
System.out.println("bike is created");} a class, that class must be abstract.
abstract void run( ); class Bike12{
void changeGear( ){ abstract void run();
System.out.println("gear changed");} }
} Output: compile time error
class Honda extends Bike{
Rule: If you are extending any abstract
void run( ){
class that has abstract method, you
must either provide the implementation
System.out.println("running safely..");}
of the method or make this class
}
abstract.
class TestAbstraction2{
public static void main(String args[ ]){ Bike
obj = new Honda();
obj.run(); obj.changeGear();
}
}
Output: bike is created
running safely.. gear
changed
Interface in Java
An interface in java is a blueprint of a class. It has static constants and abstract methods only. The
interface in java is a mechanism to achieve fully abstraction. There can be only abstract methods in
the java interface not method body. It is used to achieve fully abstraction and multiple inheritance in
Java.
Java Interface also represents IS-A relationship. It
cannot be instantiated just like abstract class.
There are mainly three reasons to use interface. They are given below.
 It is used to achieve fully abstraction.
 By interface, we can support the functionality of multiple inheritance.
 It can be used to achieve loose coupling.
NOTE: The java compiler adds public and abstract keywords before the interface method
and public, static and final keywords before data members.
Understanding relationship between classes and interfaces

As shown in the figure given above, a class extends another class, an interface extends another
interface but a class implements an interface.
II

Simple example of Java interface


In this example, Printable interface have only one method, its implementation is provided in the A
class.
interface printable{
void print();
}
class A6 implements printable{
public void print(){System.out.println("Hello");}
public static void main(String args[]){ A6 obj
= new A6();
obj.print();
}
}
Output: Hello
Multiple inheritance in Java by interface
If a class implements multiple interfaces, or an interface extends multiple interfaces i.e. known as
multiple inheritance.
interface Printable{
void print();
}
interface Showable{
void show();
}
class A7 implements Printable,Showable{
public void print(){System.out.println("Hello");} public
void show(){System.out.println("Welcome");} public static
void main(String args[]){
A7 obj = new A7(); obj.print();
obj.show();
} }
Output: Hello
Welcome
Interface inheritance
A class implements interface but one interface extends another interface .
interface Printable{
void print();
}
interface Showable extends Printable{
void show();
}
class Testinterface2 implements Showable{
public void print(){System.out.println("Hello");} public void
show(){System.out.println("Welcome");} public static void
main(String args[]){
Testinterface2 obj = new Testinterface2(); obj.print();
obj.show(); Output: Hello
} } Welcome
II

A programmer uses an abstract class when there are some common features shared by all the
objects. Interfaces are written when the programmer wants to leave the implementation to third party
vendors. An interface is a specification of method prototypes. All the methods in an interface are
abstract methods.
 An interface is a specification of method prototypes.
 An interface contains zero or more abstract methods.
 All the methods of interface are public, abstract by default.
 Once an interface is written any third party vendor can implement it.
 All the methods of the interface should be implemented in its implementation classes.
 If any one of the method is not implemented, then that implementation class should
be declared as abstract.
 We cannot create an object to an interface.
 We can create a reference variable to an interface.
 An interface cannot implement another interface.
 An interface can extend another interface.
 A class can implement multiple interfaces.
Defining an interface:
An interface is defined much like a class.
This is the general form of an interface:
access interface name
{
return-type method-name1(parameter-list); return-
type method-name2(parameter-list); type final-
varname1 = value;
type final-varname2 = value;
// ...
return-type method-nameN(parameter-list); type
final-varnameN = value;
}
Here is an example of an interface definition. It declares a simple interface that contains one method
called callback() that takes a single integer parameter.
interface Callback
{
void callback(int param);
}
Implementing Interfaces
Once an interface has been defined, one or more classes can implement that interface. The general
form of a class that includes the implements clause looks like this:
class classname [extends superclass] [implements interface [,interface...]]
{
// class-body
}
If a class implements more than one interface, the interfaces are separated with a comma. If a class
implements two interfaces that declare the same method, then the same method will be used by
clients of either interface. The methods that implement an interface must be declared public.
II

Accessing Implementations through Interface References:


You can declare variables as object references that use an interface rather than a class type. Any
instance of any class that implements the declared interface can be referred to by such a variable.
This is one of the key features of interfaces. The method to be executed is looked up dynamically at
run time, allowing classes to be created later than the code which calls methods on them. The calling
code can dispatch through an interface without having to know anything about the ―callee.‖
The following example calls the callback( ) method via an interface reference variable:
class TestIface
{
public static void main(String args[])
{
Callback c = new Client();
c.callback(42);
}
}
Output: callback called with 42
// Another implementation of Callback. class
AnotherClient implements Callback
{
// Implement Callback&#39;s interface public
void callback(int p)
{
System.out.println("Another version of callback");
System.out.println("p squared is "+ (p*p));
}
}
Now, try the following class:
class TestIface2
{
public static void main(String args[])
{
Callback c = new Client();
AnotherClient ob = new AnotherClient();
c.callback(42);
c = ob; // c now refers to AnotherClient object
c.callback(42);
}
}
Output: callback called with 42
Another version of callback p
squared is 1764
As you can see, the version of callback( ) that is called is determined by the type of object that c
refers to at run time.
EXTENDING INTERFACES:
One interface can inherit another by use of the keyword extends. The syntax is the same as for
inheriting classes. When a class implements an interface that inherits another interface, it must
provide implementations for all methods defined within the interface inheritance chain.
II

Following is an example: // One interface can extend one or more interfaces.. interface A
{
void meth1(); void
meth2();
}
// B now includes meth1() and meth2() -- it adds meth3().
interface B extends A { void
meth3();
}
// This class must implement all of A and B class
MyClass implements B {
public void meth1() {
System.out.println("Implement meth1().");
}
public void meth2() {
System.out.println("Implement meth2().");
}
public void meth3() {
System.out.println("Implement meth3().");
}
}
class IFExtend {
public static void main(String arg[]) {
MyClass ob = new MyClass(); ob.meth1();
ob.meth2();
ob.meth3();
}
}
Difference between abstract class and interface
Abstract class and interface both are used to achieve abstraction where we can declare the abstract
methods. Abstract class and interface both can't be instantiated. But there are many differences
between abstract class and interface that are given below.
Abstract class Interface
1) Abstract class can have abstract and non- Interface can have only
abstractmethods. abstract methods.
2) Abstract class doesn't support multiple Interface supports multiple
inheritance. inheritance.
3) Abstract class can have final, non-final, static Interface has only static and final
and non-static variables. variables.
4) Abstract class can have static methods, main Interface can't have static methods, main
method and constructor. method or constructor.
II

5) Abstract class can provide the Interface can't provide the


implementation of interface. implementation of abstract class.
6) The abstract keyword is used to declare The interface keyword is used to
abstract class. declare interface.
7) Example: Example:
public abstract class Shape{ public public interface Drawable{ void
abstract void draw(); draw();
} }
Simply, abstract class achieves partial abstraction (0 to 100%) whereas interface achieves fully
abstraction (100%).
Example of abstract class and interface in Java
//Creating interface that has 4 methods
interface A
{
void a();//bydefault, public and abstract
void b();
void c();
void d();
}
//Creating abstract class that provides the implementation of one method of A interface
abstract class B implements A
{
public void c(){System.out.println("I am C");
}
}
//Creating subclass of abstract class, now we need to provide the implementation of methods
class M extends B
{
public void a(){System.out.println("I am a");}
public void b(){System.out.println("I am b");}
public void d(){System.out.println("I am d");}
}
//Creating a test class that calls the methods of A interface
class Test5
{
public static void main(String args[])
{
A a=new M(); a.a();
a.b();
a.c();
a.d();
}
}
Output:
I am a I am b I am c I am d
II

Packages in JAVA:
Java provides a mechanism for partitioning the class name space into more manageable chunks.
This mechanism is the package. The package is both a naming and a visibility control mechanism.
You can define classes inside a package that are not accessible by code outside that package.
You can also define class members that are only exposed to other members of the same package.
A java package is a group of similar types of classes, interfaces and sub-packages. Package in
java can be categorized in two form, built-in package and user-defined package.
There are many built-in packages such as java, lang, awt, javax, swing, net, io, util, sql etc.
Advantage of Java Package
1) Java package is used to categorize the classes and interfaces so that they can be easily
maintained.
2) Java package provides access protection.
3) Java package removes naming collision.
4) A group of package called a library. The classes and interfaces of a package are likes
books in a library and can be reused several times.
Defining a Package:
• Creating a package is quite easy: simply include a package command as the first
statement in a Java source file. Any classes declared within that file will belong to the specified
package. The package statement defines a name space in which classes are stored.
Creating a Package:
• The general form of the package statement:
package pkg; //Here, pkg is the name of the package.

• For example, the following statement creates a package called MyPackage.


package MyPackage;
The package keyword is used to create a package in java.
Java uses file system directories to store packages. For example, the .class files for any
classes you declare to be part of MyPackage must be stored in a directory called MyPackage.
Note: Remember that the directory name must match the package name exactly.
More than one file can include the same package statement. The package Statement simply specifies
to which package the classes defined in a file belong. You can create a hierarchy of packages. To do
so, simply separate each package name from the one above it by use of a period.
•The general form of a multileveled package statement is shown here:
package pkg1[.pkg2[.pkg3]];
•A package hierarchy must be reflected in the file system of your Java development.
•You cannot rename a package without renaming the directory in which the classes are stored.
II

//save as Simple.java
package mypack; public
class Simple{
public static void main(String args[]){
System.out.println("Welcome to package");
}
}
How to compile java package
If you are not using any IDE, you need to follow the syntax given below: javac -
d directory javafilename
For example: javac -d . Simple.java
The -d switch specifies the destination where to put the generated class file. You can use any
directory name like /home (in case of Linux), d:/abc (in case of windows) etc. If you want to keep
the package within the same directory, you can use . (dot).
How to run java package program
You need to use fully qualified name e.g. mypack.Simple etc to run the class.
To Compile: javac -d . Simple.java
To Run: java mypack.Simple
Output: Welcome to package
II
How to access package from another package?
There are three ways to access the package from outside the package.
1. import package.*;
2. import package.classname;
3. fully qualified name.
1) Using packagename.*
If you use package.* then all the classes and interfaces of this package will be accessible but not
subpackages. The import keyword is used to make the classes and interface of another package
accessible to the current package.
Example of package that import the packagename.*
//save by A.java
package pack; public
class A{
public void msg(){System.out.println(" Hello");
}}
//save by B.java package javac -d . A.java
mypack; import pack.*; javac -d . B.java
class B{ java mypack.B
public static void main(String args[]){ A obj = new A();
obj.msg();
}
} Output: Hello
2) Using packagename.classname
If you import package.classname then only declared class of this package will be accessible.
Example of package by import package.classname
//save by A.java //save by B.java package
package pack; public mypack; import pack.A;
class A{
public void msg(){System.out.println(" class B1{
Hello1"); public static void main(String args[]){ A obj
} = new A();
} obj.msg();
} javac -d . A.java
} javac -d . B1.java
java mypack.B1
Output: Hello1
3) Using fully qualified name
If you use fully qualified name then only declared class of this package will be accessible. Now there
is no need to import. But you need to use fully qualified name every time when you are accessing the
class or interface. It is generally used when two packages have same class name e.g. java.util and
java.sql packages contain Date class.
Example of package by import fully qualified name
//save by A.java
package pack; public
class A{
public void msg(){System.out.println("Hello2"); }
} javac -d . A.java
//save by B.java package javac -d . B2.java
mypack; class B2{ java mypack.B2
public static void main(String args[]){
pack.A obj = new pack.A();//using fully qualified name
obj.msg();
}
} Output: Hello
II
• packages are able to provide the following advantages.
• Modularity
• Abstraction
• Security
• Sharability
• Reusability
• The classes contained in the packages can be easily reused in any program.
• In packages, class name can be unique. That is, two classes in two different packages can have the same
name.
• Packages provide a way to hide classes thus preventing other programs or packages from accessing classes
that are meant for internal use only.
• Packages provide a way for separating designing from coding.
• Packages provide the reusability beyond the programs.
• With the package we can reuse the classes and interfaces, so it will reduce size and time.

• There are two types of packages in Java:


• Built-in packages
• User-defined packages:-
The users of the Java language can also create their own packages. They are called user-defined
packages.

Static import
Static import is a feature introduced in Java programming language (versions 5 and above) that allows
members (fields and methods) defined in a class as public static to be used in Java code without specifying the
class in which the field is defined.
Example:
import static java.lang.System.*;
class Test {
public static void main(String args[]) {
// We don't need to use 'System.out‘ as imported using static.
out.println(“WELCOME");
}
}
Example1:
Package packagel;
public class ClassA
{
public void displayA(){
System.out.println("Class A");
}}
Importing the above packagel in program PackageTest1.java:
Import package1.ClassA;
class PackageTest1
{
public static void main(String args[])
{
ClassA objectA = new ClassA();
objectA . displayA();
}
}
Output:
ClassA
Example2:
package pack;
public class Addition
{
private double d1,d2;
public Addition(double a,double b)
{ d1 = a;
d2 = b;
}
public void sum()
{ System.out.println ("Sum of two given numbers is : " + (d1+d2) );
}
}

Example3: Using Interface in packages


package student;//student.java
public interface Students {
void RollNo();
void course();
void marks();
}
import student.*;
class Test1 implements Students {
void RollNo() {
System.out.println("18"); }
void course() { System.out.println(―Java"); }
void marks() { System.out.println(―65"); }
}
class Test {
public static void main(String[] args) {
Test1 t = new Test1();
t.RollNo();
t.course();
t.marks();
}
}

You might also like