0% found this document useful (0 votes)
4 views37 pages

Datascience IV Java Unit 1, 2

Java is an object-oriented, platform-independent programming language developed by James Gosling in 1995, widely used for internet programming and Android applications. It includes a Java Development Kit (JDK) for program development, which consists of tools like compilers and interpreters, and features a robust standard library. Key characteristics of Java include security, portability, high performance, and support for multithreading and dynamic linking.

Uploaded by

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

Datascience IV Java Unit 1, 2

Java is an object-oriented, platform-independent programming language developed by James Gosling in 1995, widely used for internet programming and Android applications. It includes a Java Development Kit (JDK) for program development, which consists of tools like compilers and interpreters, and features a robust standard library. Key characteristics of Java include security, portability, high performance, and support for multithreading and dynamic linking.

Uploaded by

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

1

UNIT – I Java Introduction


1. Java is an object-oriented, class-based, secured and general-purpose computer-
programming language.
2. JAVA was developed by JAMES GOSLINGat Sun Microsystemsin the year 1995.
3. It helps to create Reusable Code and Modular Programs.
4. Today ,Java is used for Internet Programming in the Distributed Environment of the
internet and for Android smartphone applications and the Internet Of Things.
5. It is a general-purpose programming language for developers to write once run
anywherei.e, compiled Java code can run on all platforms that support Java
without the need to recompile.
6. Java programs are Platform Independent Language which means they can be run on
any operating system with any processor
7. Java has features of C and C++ and has obtained its format from C, and OOP features
from C++.
Java Essentials

1. Java environment includes a large number of development tools and hundreds of


classes and methods.
2. Java program development requires a java software development kit SDK , which
includes a compiler, interpreter, documentation generator and other tools like IDE.
3. The development tools are part of the system known as Java Development Kit (JDK)
and the classes and methods are part of Java Standard Library (JSL) also known as
the Application Programming Interface(API).
4. JDK :
It is a collection of tools that are used for developing java programs. It includes:
1.appletviewer ( for viewing java applets)
2. javac (java compiler)
3. java (java interpreter)
4. javap (java disassembler)
5. javah (for c header files)
6. javadoc (for creating html documents)
7. jdb (java debugger)

1. To create a java program, we need to create a source code file using a text editor.
2. The source code is complied using the java compiler javac and executed using java
interpreter java.
3. The java debugger jdb is used to find error .
4. A compiled java program can be converted into a source code with the help of disassembler
javap.

1
2

Application programming interface (API)


The java standard library for API includes hundreds of classes and methods grouped into
packages as follows :
1.language support package 4.Networking package
2. Utilities package 5. AWT package
3. Input/output package 6. Applet package
Java Runtime environment (JRE)
JRE allows execution of program developed in java which contains
1. JVM (java virtual machine)
2. Runtime class libraries
3. User interface toolkit (AWT and Swing)
Features of Java
Simple , small and familiar Distributed
Compiled and interpreted Multithread and interactive
Platform independent and portable High performance
Object oriented Dynamic and extensible
Robust and secure Easy application development
Simple small and familar
1. Java is simple as it does not use pointers, preprocessor, header files, goto , operator
overloading and multiple inheritance.
2. Java is familiar because syntax is based on c++, easy to learn, and its syntax is simple,
small and easy to understand.
Object-oriented
1. Java is a true object-oriented programming language & supports all oops concepts
like Object, class, Abstraction, Encapsulation, Inheritance , Polymorphism .
2. Everything in Java is an object.
3. All java program code and data is defined within objects and classes .
4. Java library is vast set of classes , arranged in packages, that we can use in our
programs
Platform Independent and portable
1. Java is platform independent were Java programs can be easily be transferred from one
computer to another,(write once, run anywhere, anytime).
2. Changes and upgrades in OS, processors and system resources will not force any changes
in java program
3. This is the reason java has become popular language for internet programming which
interconnects different kinds of systems worldwide.
Portability
1. Java ensures portability in two ways.
2. First java compiler generates byte code instructions that can be implemented on any
machine.
3. Secondly, the size of the primitive data types is machine independent.

2
3

Secured
1. Security becomes an important issue for a language that is used for programming
internet.
2. Attack of viruses and misuse of resources are everywhere.
3. Java systems not only verify all memory access but also ensure that no virus attack java
programs. so Java is best known for its security. With Java, we can develop virus-free
systems.
4.Absence of pointers in java ensures that java programs cannot access memory locations
without proper authorization.
5. Java Programs run inside a virtual machine sandbox

Robust (strong)
Java is robust language because:
1. It uses strong memory management& provides many safeguards to ensure reliable
code.
2. It has strict compile time and runtime checking for data types.
3. It avoids security problems because pointers are not used.
4. There is Automatic Garbage Collection in java which runs on the Java Virtual
Machine to free objects which are not being used by a Java application anymore.
5. There are Exception Handling to handle runtime errors and eliminates system crash.
High-performance
Java programs are faster in execution when compared to other traditional interpreted
programming languages because Java byte code is close to native code.
Distributed
1. Java is designed as a distributed language for creating applications on networks.
2. It has the ability share both data and programs.
Multi-threaded and Interactive
1. Multithreaded means handling multiple tasks simultaneously.
2. Java supports multithread programs .
3. This means that we need not wait for application to finish one task before beginning
another.
4. A thread is like a separate program, executing concurrently and It shares a common
memory area. Eg: we can listen to audio while downloading image.
Dynamic and extensible
1. Java is a dynamic language. Java is capable of dynamically linking in new class libraries,
methods and object.
2. Java programs support functions written in c/c++. These functions are known as native
methods. 3. These methods are linked dynamically at runtime.
4. Java supports dynamic compilation and automatic memory management (garbage
collection).

3
4

4
5

Java Virtual Machine (JVM)


1. Java Virtual Machine (JVM) is an abstract machine (which does not exist physically)
responsible for compiling and executing Java code. It is a part of the Java Runtime
Environment (JRE) which calls the main function of a program.
JVM(Java Virtual Machine) acts as a run-time engine to run Java applications.
2. When we execute a Java program ,JVM converts the byte code to the machine-
specific code.
3. In other programming languages, the compiler produces machine code for a
particular system however java compiler produces code for a virtual machine known
as JVMFirst, java compiler converts java program into bytecode. (filename.java -
>filename.class)
4. Bytecode is an intermediate code between source code and machine code.
5. This .class file goes into various steps when we run it. These steps together
describe the whole JVM.

Features of JVM
A. It converts byte code to the machine language.
B. JVM provides basic java functions like memory management, security, garbage
collection, etc.
C. Runs the program by utilizing JRE’s libraries and files.
D. JVM is an integral part of JRE.
E. It can execute the java program line by line. Therefore, it is also known as an
interpreter.
F. The main functions of JVM include loading, linking, initializing, and compiling the
program.
G. Note: JVM can’t be installed alone. As JVM is a part of JRE, you need to install JRE.
JVM comes within it.
6. JVM performs the following operations:
A. Loads code
B. Verifies code
C. Executes code
D. Provides runtime environment
7. JVM provides definitions for the following
A. Memory area
B. Class file format
C. Register set
D. Garbage collected heap
E. Fatal error reporting

5
6

creating, Compiling, and Executing a Java Program


In java two types of programs can be developed:
1.Stand-Alone Applications 2.Web Applets
Standalone applications are programs written in java to perform tasks on a standalone local
computer. Executing standalone programs involves two steps:
1. Compiling source code to bytecode using javac compiler.
2. Executing the bytecode program using java interpreter.
Web applets are small java programs developed for internet applications .
An applet located in server can be downloaded via internet and executed on a local
computer using browser.

Step 1: Creating a Java Program


use any text editor or IDE to create and edit a Java source-code file.
Open notepad and save program as Welcome.java
public class Hello
{
public static void main(String[] args)
{
System.out.println("HI");
}
}
Step 2: Compiling a Java Program
A Java compiler translates a Java source file(Welcome.java) into a Java bytecode file
(Welcome.class) as
D:\ds>javac Hello.java

If there are no syntax errors, the compiler generates a bytecode file with a .class extension
as Welcome.class
Step 3: Executing a Java Program : use java command to execute the bytecode:
D:\ds>java Hello output : HI

6
7

1.class keyword is used to declare a class in Java.


2.public keyword is an access modifier that represents visibility. It means it is visible to all.

static :
1. static is a keyword, if we declare any method as static, it is known as static method.
2. no need to create object to invoke the static method
3. Static method are executed only once in the program.
4. main() method of java executes only once throughout the java program execution and
hence it declare must be static.
5. The main method is executed by the JVM, so it doesn't require to create object to invoke
the main method. So it saves memory.
void:
void is the return type of the method. It means it doesn't return any value. main() Method in
Java program execution starts with main(). If any class contain main() method known as
main class.
main() Method :
program execution starts with main(). If any class contain main() method known as main
class.
String args[] :
String is class
Args are array of string arguments
String args[] is a String array used to hold command line arguments in the form of String
values.
If any input value is passed through the command prompt at the time of running of the
program is known as command line argument .
By default every command line argument will be treated as string value and those are
stored in a string array of main() method.
Output statement:

System.out.println("hello"); -> is output statement.


System –> Class
out ->static Object
println() –>method

System:
It is the name of standard class that contains objects that encapsulates the standard I/O
devices of your system. It is contained in the package java.lang. (default package)
out:
The object out represents output stream and is the static data member of the class System.
println:
The println() is method of out object that takes the text string as an argument and displays it
to the standard output i.e screen.

7
8

Data types
I. Variables are the names given to memory address for storing data values.
Datatype variableName = value; int a = 1000;
II. Data types specify the different sizes and values that can be stored in the variable.
In java, there are 2 types of data types.
1) Primitive data types 2) Non-primitive data types ( Arrays ,Strings, Classes, Interfaces)

1) Primitive data types


In Java, we have eight primitive data types: boolean, char, byte, short, int, long, float and
double.
portability of java is because the size of these primitive data types do not change from one
operating system to another.
1. byte, short, int and long data types are used for storing whole numbers.
2. float and double are used for fractional numbers.
3. boolean data type is used for variables that holds either true or false.
4. char is used for storing characters(letters).
5. String - stores text, such as "Hello". String values are surrounded by double quotes
data Default Default Range Example stores
type Value size

boolean false 1 bit true and false boolean status = false true or false

char '\u0000' 2 byte 65,535 char ch = 'A' Single character

byte 0 1 byte (-28) to (28 -1) byte a = 10 Whole numbers


-128 to 127 (inclusive)
short 0 2 byte (-216) to (216 -1) Short s = 100 stores integers
(whole numbers),
without decimals
int 0 4 byte (-231) to (231 -1) int a = 1000 stores integers
(whole numbers),
without decimals
long 0L 8 byte (-263) to (263 -1) long a = 100000L stores integers
(whole numbers),
without decimals
float 0.0f 4 byte Upto7 decimal digits float f1 = 234.5f stores floating
point numbers,
with decimals,
double 0.0d 8 byte Upto16 decimal double d1 = 12. stores floating
digits 3 point numbers,
with decimals,

8
9

program to show java datatypes


class Datatype
{
public static void main(String[]args)
{
byte b=10; char ch = 'A'; short s = 1000;
int m = 23643; long a = 100000L; float f1 = 234.5f ;
double d1 = 12.3;
system.out.println(b);
system.out.println(ch);
system.out.println(s);
system.out.println(m);
system.out.println(a);
system.out.println(f1);
system.out.println(d1);
}
}

Type Casting/type conversion


In java, Converting one primitive datatype into another is known as type casting (type
conversion). There are two ways to convert : Widening and Narrowing.
Widening(Up casting) :
Converting a lower datatype to a higher datatype is known as widening. In this case the
casting/conversion is done automatically by the compiler without user
involvement.therefore, it is known as Implicit Type Casting.

public class Wide


{
publicstaticvoid main(Stringargs[])
{
inti = 100;
floatf = l; // casting from int to float
System.out.println(f);
} } Output 100.0
Narrowing (down casting):

Converting a higher datatype to a lower datatype is known as narrowing. In this case the
casting/conversion is not done automatically, you need to convert explicitly using the cast operator
“( )” explicitly. Therefore, it is known as Explicit Type Casting.

Variable=(type)variable;

9
10

public class Narrow


{
publicstaticvoid main(Stringargs[])
{
doubled = 100.04;
longl = (long)d; // casting from double to long
System.out.println(f);
}
}
Inboxing: conversion of primitive into non-primitive
int x=10;
Integer y=x;
Outboxing: conversion of non-primitive into primitive
Integerx=10;
int y=x;
Note: Integer is class ,int is primitive data type

command-line argument
1. The java command-line argument is an argument that is passed at the time of
running the java program.
2. The arguments passed from the keyboard can be received in the java program and it
can be used as an input.
3. It provides a way to check the behavior of the program for the different values.
4. We can pass both strings and primitive data types(int, double, float, char, etc) as
command-line arguments.
5. The arguments will be converted to strings and passed into the
main method string array argument.
6. In java program, main function accepts string array as an
argument.
7. The args[] contains the total number of arguments.
8. We can check these arguments using args.length method.
9. The first argument is the file name always.

class Testcmd
{
public static void main(String args[])
{
System.out.println(" first argument is: " + args[0]);
System.out.println("second argument is: " + args[1]);
}
}
Output:
D:\>javac Testcmd
D:\>java Testcmd hello hai
args[0] ->cmd
args[1] -> hello

10
11

args[2] ->hai
Java conditional statements
Java has specific statements that allow us to check a condition and execute certain parts of
code depending on whether the condition is true or false. Such statements are called
conditional statements.
In Java, there are two forms of conditional statements:•
1. if-else statement, to choose between two alternatives
2. switch statement, to choose between multiple alternatives
Java If-else Statement
The Java if statement is used to test the condition. It checks boolean condition: true or false.
There are various types of if statement in java.
1. if statement
2. if-else statement
3. if-else-if ladder
4. nested if statement
Java if Statement :The Java if statement tests the condition. It executes the if block if condition is
true.
Syntax: //Java Program to show if statement.
if(condition) public class age
{ {
code to be executed public static void main(String[] args)
}
{
int age=20;
if(age>18)
{
System.out.print("Age is greater than 18");
}
}
}

Java if-else Statement


The if-else statement also tests the condition. if condition is true It executes the statements
otherwise else statements are executed.
Syntax: public class large
if(condition) {
{ public static void main(String[] args)
code if condition is true
{
}
else int a=10,b =20;
{ if(a>b)
code if condition is false {
} System.out.println("a largest");
}
else
{
System.out.println("b largest");
}

11
12

if-else-if ladder Statement


The if-else-if ladder statement executes one condition from multiple statements.
Syntax: public class largest
if(condition1) {
{ public static void main(String[] args)
code to be executed if condition1 is true
{
}
else if(condition2) int a=10,b=20,c=30;
{ if(a>b&&a>c)
code to be executed if condition2 is true System.out.println(“largest” + a);
} else if(b>c&&b>a)
else if(condition3) System.out.println(“largest” + b);
{ else
code to be executed if condition3 is true
System.out.println(“largest” + c);
}
... }
else }
{
code to be executed if all the conditions are false
}
Java Nested if statement
The nested if statement represents the if block within another if block. Here, the inner if
block condition executes only when outer if block condition is true.
Syntax:
if(condition)
{
code to be executed
if(condition)
{
code to be executed
}
}
Java Switch Statement
1. The Java switch statement executes one statement from multiple conditions.
2. It is like if-else-if ladder statement.
3. the switch statement checks the equality of a variable against multiple values.
4. The case value must match with switch expression(byte, short, int, long string.
5. if correct match found it exectues the statement block of that case . if no match is found ,
default is exectued.
6. The case value must be literal or constant. It doesn't allow variables.
7. The case values must be unique but not duplicate value
8. Every case should end with break keyword.
9. If no match is found , default is executed.
10. it is used in menu driven programs.

12
13

Syntax:
switch(expression)
{
case value1: code to be executed; break;
case value2: code to be executed; break;
case value3: code to be executed; break;
......
default: execute code if all cases are not matched;
}
Program to show switch

public class vowel


{
public static void main(String[] args)
{
char alpha=’a’;
switch(alpha)
{
case ‘a’: System.out.println("vowel"); break;
case ‘e’: System.out.println("vowel"); break;
case ‘i’: System.out.println("vowel"); break;
case ‘o’: System.out.println("vowel"); break;
case ‘u’: System.out.println("vowel"); break;
default: System.out.println("not vowel");
}
}
}

13
14

Loops in Java
The process of executing repeatedly block of statments for specified number of times or till
given codigion is satisfied is known as looping.
Types of loops:
1.while loop 2.do-while loop 3.for loop

while loop do while loop for loop


It is pre-test loop It is post-test loop It is pre-test loop
Condition is given before Condition is given after Condition is given before
statements . statements . statements .
First condition is checkecd. Without checking condition, First condition is checkecd.
If condition is true then code statements are exectued for If condition is true then code will
will be executed repeatedly. first time. be executed repeatedly.
If condition is false loop will be If the number of iteration is If condition is false loop will be
stopped. not fixed, use while loop. stopped.
If the number of iteration is If the number of iteration is not
not fixed, use while loop. fixed, use while loop.
while(condition) do for (init; condition; incr/decr)
{ { {
code to be executed code to be executed code to be executed
} }while(condition); }
for(int i=1;i<=10;i++)
int i=1; int i=1; {
while(i<=10) do System.out.println(i);
{ { }
System.out.println(i); System.out.println(i);
i++; i++;
} }while(i<=10);
public class Test2 public class Test3 public class Test1
{ { {
p s v main(String[] args) p s v main(String[] args) p s v main(String[] args)
{ { {
int i=1; int i=1; for( int i=1; i<=10 ;i++)
do System.out.println(i);
while(i<=10)
{ }
{
}
System.out.println(i); System.out.println(i);
i++; i++;
} }while(i<=10);
} }
} }

14
15

Defining classes :creating objects and Classes in Java


Java is an object-oriented programming language. Everything in Java is associated with classes and
objects, along with its attributes and methods.
object class
1. An object is a real-world entity. 1. A class is a user defined blueprint or
2. An object is a runtime entity. prototype from which objects are
3. The object is an entity which has created.
state and behavior. e.g. table,car 2. It represents thes et of properties or
methods that are common to all objects
4. The object is an instance of a class.
of one type.
5. It can be physical or logical (tangible
3. It is a logical entity.
and intangible).
4. It can't be physical.
6. Example of intangible object is the
A class in Java can contain:
banking system.
Fields , Methods , Constructors , Blocks
7. An object has three characteristics:
A. State: represents the data (value) of Nested classes
an object.
B. Behavior: represents the behavior A. class is created using class keyword
(functionality) of an object such as B. class is created only once and no memory
deposit, withdraw, etc. is allocated.
C. Identity: An object identity is typically C. In Java, an object is created from a class.
implemented via a unique ID. The value
of the ID is not visible to the external Create an object called "s" and print the value
user. of age:
Objects are created using new keyword
Object is created as many times public class Student
For object memory is allocated when it is {
created.
Create a Class int age = 20;
To create a class, use the keyword class
Syntax to declare a class: public static void main(String[] args)
class Classname {
{
Fields declaration; Student s = new Student();
Method declaration;
System.out.println(s.age);
}
Example: }
Create a class named "Student" with a variable
age: }

public class Student The new keyword is used to allocate memory at


{ runtime. All objects get memory in Heap
int age = 20; memory area.
}

15
16

Note:a class should always start with an


uppercase first letter, and that the name of the
java file should match the class name.

A class can contain any of the following variable types.

Local variables –
Variables defined inside methods, constructors or blocks are called local variables.
The variable will be declared and initialized within the method and the variable will be destroyed
when the method has completed

Instance variables –
Instance variables are variables within a class but outside any method.
These variables are initialized when the class is instantiated.
Instance variables can be accessed from inside any method, constructor or blocks of that particular
class.

Class variables –
Class variables are variables declared within a class, outside any method, with the
static keyword.

16
17

Unit II
METHOD DECLARATION AND INVOCATION
A method is a block of code which only runs when it is called.
You can pass data, known as parameters, into a method.
Methods are used to perform certain actions, and they are also known as functions.
Use of methods :
To reuse code: define the code once, and use it many times.
Create a Method
A method must be declared within a class. It is defined with the name of the method,
followed by parentheses (). Java provides some pre-defined methods, such as
System.out.println()
Call a Method
To call a method in Java, write the method's name followed by two parentheses () and a
semicolon;
Program:
public class Test
{
void Hello()
{
System.out.println("hi");
}

public static void main(String[] args)


{
Hello();
}
}

17
18

constructors in Java
1. A constructor in Java is a special method that is used to initialize objects.
2. A constructor contains block of statements similar to a method
3. It is invoked when an instance of the object is created, and memory is allocated for
the object.
4. It is a special type of method which is used to initialize the object.
5. It can be used to set initial values for object attributes
When is a constructor invoked
A. Every time an object is created using new() keyword, at least one constructor is
called.
It calls a default constructor.
B. It is called constructor because it constructs the values at the time of object creation.
C. It is not necessary to write a constructor for a class.
D. It is because java compiler creates a default constructor if your class doesn't have
any.
Rules for creating Java constructor
1) Constructor name and class name must be same.
2) A Constructor must have no return type.
3) A constructor cannot be abstract, static, final, and synchronized
Types of Java constructors
1.Default constructor (no-arg constructor) 2.Parameterized constructor
Java Default Constructor
A constructor is called "Default Constructor" when it doesn't have any parameter.
The default constructor is used to provide the default values to the object like 0, null, etc.,
depending on the type. If there is no constructor in a class, compiler automatically creates a default
constructor.
Syntax
classname( )
{
}
program to show default constructor that displays the default values
class Student3
{
int rno;
String name;
void display()
{
System.out.println( rno +" " + name );
}
public static void main(String args[])
{
Student3 s1=new Student3(); //creating objects

18
19

Student3 s2=new Student3();


s1.display(); //displaying values of the object
s2.display();
}
}
Java Parameterized Constructor
A constructor which has a specific number of parameters is called a parameterized constructor.
The parameterized constructor is used to provide different/same values to the distinct objects.
Parameters are also known as arguments
Syntax
classname(parameters )
{
}

Program to show parameterized constructor


class Student4
{
int rno;
String name;
//creating a parameterized constructor
Student4(int i,String n)
{
rno= i;
name = n;
}
//method to display the values
void display( )
{
System.out.println(rno+" "+name);
}

public static void main(String args[])


{
//creating objects and passing values
Student4 s1 = new Student4(25,"anu");
Student4 s2 = new Student4(26,"priya");

//calling method to display the values of object


s1.display();
s2.display();
}
}

Output:
25 anu
26 priya

19
20

Constructor Overloading
1) In Java, a constructor is just like a method but without return type.
2) It can also be overloaded like Java methods.
3) Constructor overloading in Java is a technique of having more than one constructor with
different parameter lists.
4) They are arranged in a way that each constructor performs a different task.
5) They are differentiated by the compiler by the number of parameters in the list and their
types.
Program to show Constructor Overloading
class Student5
{
int rno;
String name;
int age;

Student5(int i, String n) //creating two arg constructor


{
rno= i;
name = n;
}

Student5(int i ,String n, int a) //creating three arg constructor


{
rno= i;
name = n;
age=a;
}
void display()
{
System.out.println(rno + " " + name + " " + age);
}

public static void main(String args[])


{
Student5 s1 = new Student5(25,"anu");
Student5 s2 = new Student5(26,"priya",20);
s1.display();
s2.display();
}
}
Output:
25 anu 0
26 priya 20

20
21

this keyword
In java, this is a keyword and a reference variable that refers to the current object.

Usage of java this keyword


1) this can be used to refer current class instance variable.
2) this can be used to invoke current class method (implicitly)
3) this() can be used to invoke current class constructor.
4) this can be passed as an argument in the method call.
5) this can be passed as argument in the constructor call.
6) this can be used to return the current class instance from the method.
1) this: to refer current class instance variable
The this keyword can be used to refer current class instance variable. If there is ambiguity between
the instance variables and parameters, this keyword resolves the problem of ambiguity.

class Student
{
int rollno;
String name;
Float fee;
Student(int rollno,String name,float fee)
{
this.rollno=rollno;
this.name=name;
this.fee=fee;
}
void display()
{
System.out.println(rollno+" "+name+" "+fee);}
}

class Testthis
{
public static void main(String args[]){
Student s1=new Student(11,"anu",5000f);
Student s2=new Student(12,"suma",6000f);
s1.display();
s2.display();
}}

21
22

Output: 11,"anu",5000f 12,"suma",6000f

Java Array
1. An array is a collection of similar datatype elements that are stored in continuoues memory
location.
2. Arrays are used to store multiple values in a single variable, instead of declaring separate
variables for each value.
3. Java array is an object which contains elements of a similar data type. It is a data structure
where we store similar elements. We can store only a fixed set of elements in the array.
4. Array in java is index-based, the first element of the array is stored at the 0 index.

Advantages
1. Code Optimization: It makes the code optimized, we can retrieve or sort the data efficiently.
2. Random access: We can get any data located at an index position.
Disadvantages
1. Size Limit: We can store only the fixed size of elements in the array. It doesn't grow its size
at runtime. To solve this problem, collection framework is used in Java which grows
automatically.
Types of Array in java
There are two types of array. 1. Single Dimensional Array2.Multidimensional Array
One or single Dimensional Array in Java
An Array defined with one variablename // Program to show array declare, initialize
and with one dimension is known as one class Testarray
dimensional array. {
public static void main(String args[])
Syntax to declare array:
{
dataType[ ] arr;
int a[]=new int[5];
dataType [ ]arr; a[0]=10; //initialization
dataType arr[ ]; a[1]=20;
example: a[2]=70;
int [] a; a[3]=40;
int a[]; a[4]=50;
int []a;
Instantiation of an Array in Java for (int i=0; i<a.length; i++)
arrayname = new datatype[size]; System.out.println(a[i]);
a=new int[3]; }
}
We can declare, instantiate and initialize the Output:
java array together by: 10 20 70 40 50
int a[ ]={11,22,33} ;

22
23

Multidimensional Arrays can be defined as an array of arrays.


Data in multidimensional arrays are stored in tabular form (rows and columns.)
Examples
int[][] arr = new int[3][5];

Three dimensional array:


int[][][] threeD_arr = new int[10][20][30];

Two – dimensional Array (2D-Array)


A. 2 D array is the simplest form of a multidimensional array.
B. 2 D array can be considered as array of one – dimensional array.
C. An Array defined with one variablename and with two dimensions is known as one
dimensional array.
Declaration : datatype[][] arrayname = new datatype[x][y];
example:
int[][] arr = new int[2][3];
int arr[][] = new int[2][3];
int [][]arr = new int[2][3];

Initialization: arrayname[rowindex][columnindex] = value;


example:
arr[0][0] = 10;
arr[0][1] = 11;
arr[1][0] = 12;
arr[1][1] = 13;
Multidimensional Java Array
class Twodarray
{
public static void main(String args[])
{
int arr[][]={{1,2,3},{2,4,5},{4,4,5}}; //declaring and initializing 2D array
for(int i=0;i<3;i++)
{
for(int j=0;j<3;j++)
{
System.out.print(arr[i][j]+" ");
}
System.out.println();
}
}
}
Output:
123
245

23
24

445
Note : java program to show matrix multiplication compulsory

Java Inner Classes


1.Inner class means one class which is a class Outer
member of another class. {
class Inner
2.Inner class or nested class is a class {
which is declared inside the class or public void show()
interface. {
3. There are four types of inner classes in System.out.println("nested class");
java. }
}
}
1) Nested Inner class
class Intest
2) Method Local inner classes {
3) Anonymous inner classes public static void main(String[] args)
4) Static nested classes {
Outer.Inner in = new Outer().new
Inner();
Syntax of Inner class
in.show();
class Outerclass }
{ }
//code
class Innerclass Output:
{ D:\>javac Intest.java
//code D:\>java Intest
}
} In a nested class method
Advantage of java inner classes
1) Nested classes represent a special type
of relationship that is it can access all the
members (data members and
methods) of outer class including private.

2) Nested classes are used to develop


more readable and maintainable code
because it logically group classes and
interfaces in one place only.

3) Code Optimization: It requires less code


to write.

24
25

Inheritance
Inheritance is a mechanism in which one object extends keyword
acquires all the properties and behaviors of a The keyword used extends is used to create
parent object.
it is used to create new classes from existing derived class from base class.
classes. Syntax :
In new class , you can reuse methods and class baseclass
fields of the parent class and also add new {
methods and fields in child class.( Code
//methods and fields
Reusability)
Inheritance represents the IS-A relationship }
which is also known as a parent-child class derivedclass extends baseclass
relationship. {
Used For Method Overriding (so runtime //methods and fields
polymorphism can be achieved) }
extends is the keyword used to inherit the
Super Class: The class whose features are
properties of a class.
inherited is known as superclass/ base class /
parent class.
The extends keyword indicates that you are
Sub Class: The new class that inherits features making a new class that derives from an
of the other class is known as a subclass / existing class.
derived class/ extended class /child class. The meaning of "extends" is to increase
the functionality.
Java single Inheritance Example
Programmer is the subclass and Employee is the superclass.
The relationship between the two classes is Programmer IS-A Employee.
It means that Programmer is a type of Employee.
Program to show single inheritance

import java.lang.*;
class Employee
{
float salary=40000;
}
class Programmer extends Employee
{
int bonus=10000;
public static void main( String args[ ] )
{
Programmer p = new Programmer();
System.out.println("Programmer salary is:" + p.salary);
System.out.println("Bonus of Programmer is:" + p.bonus);
}
}

25
26

D:\java>javac Programmer.java
D:\java>java Programmer.java

Types of inheritance in java


Single Inheritance:
1. The process of deriving one
derived class from one base class
is known as single inheritance

2.Class B extends only Class A.


3.Class A is a super class and Class
B is a Sub-class.

Multiple Inheritance:
1. The process of deriving one
derived class from several base
classes is known as multiple
inheritance

2.Java does not support multiple


inheritance.
3.Class C extends Class A and
Class B both.
Multilevel Inheritance:
1.In Multilevel Inheritance, one
class can inherit from a derived
class. 2.Hence, the derived class
becomes the base class for the
new class.
3.class C extends class B and
class B extends class A.

Hierarchical Inheritance:
1.In Hierarchical Inheritance,
one class is inherited by many
sub classes.
2.Class B, C, and D inherit the
same class A.

Hybrid Inheritance:
1.Hybrid inheritance is a
combination of Single and
Multiple inheritance.

26
27

2.all the public and protected


members of Class A are inherited
into Class D,
first via Class B and secondly via
Class C.

Method overriding
If subclass (child class) has the same method as declared in the parent class, it is known as method
overriding in Java.
Usage of Java Method Overriding Rules for Java Method Overriding
1. Method overriding is used to provide 1. The method must have the same
the specific implementation of a name as in the parent class
method which is already provided by its 2. The method must have the same
superclass. parameter as in the parent class.
2. Method overriding is used for runtime 3. There must be an IS-A relationship
polymorphism (inheritance).

example of Java Method Overriding


Consider a scenario where Bank is a class that provides functionality to get the rate of
interest. However, the rate of interest varies according to banks. For example, SBI, ICICI
and AXIS banks could provide 8%, 7%, and 9% rate of interest.
class Bank
{
int Interest();
}
class SBI extends Bank
{
int Interest()
{
return 7;
}
}
class ANDHRA extends Bank
{
Int Interest()
{
return 8;
}
}
class TestBank
{
public static void main(String args[])
{
SBI S =new SBI();
System.out.println("Rate of Interest is: "+S.Interest());

ANDHRA A=new ANDHRA();


System.out.println("Rate of Interest is: "+A.Interest());
}

27
28

Super Keyword
1. The super keyword refers to superclass (parent) objects.
2. It is used to call superclass methods, and to access the superclass constructor.
3. The most common use of the super keyword is to eliminate the confusion between
superclasses and subclasses that have methods with the same name.
4. Whenever you create the instance of subclass, an instance of parent class is created
implicitly which is referred by super reference variable.
Usage of Java super Keyword
1. super can be used to refer immediate parent class instance variable.
2. super can be used to invoke immediate parent class method.
3. super() can be used to invoke immediate parent class constructor.

import java.lang.*;
import java.string.*;
class Person
{
int id;
String name;
Person(int id,String name)
{
this.id=id;
this.name=name;
}
}
class Emp extends Person
{
float salary;
Emp(int id, String name, float salary)
{
super(id,name); //reusing parent constructor
this.salary=salary;
}
void showlay() Output:
{
System.out.println(id+" "+name + " " + salary); D:\>javac Sp.java
}
D:\>java Sp
}
class Sp 10 aruna 45000.00
{
public static void main(String[] args)

28
29

{
Emp e1=new Emp(10,"aruna",45000.00f);
e1.showlay();
}
}

final keyword
1. It is used to make a variable as a constant, Restrict method overriding, Restrict
inheritance.
2. In java language final keyword can be used in following way.
A. final keyword at variable level
B. final keyword at method level
C. final keyword at Class Level
final at variable level
A. final keyword is used to make a variable as a constant.
this is similar to const in other language.
B. A variable declared with the final keyword cannot be modified by the program after
initialization.
C. This is useful to universal constants, such as "pi".
final keyword in java example Without final keyword in java example
class circle class circle
{ {
public static final double pi=3.14159; public static final double pi=3.14159;
public static void main(string[] args) public static void main(string[] args)
{ {
system.out.println(pi); pi=4.1345f
} system.out.println(pi);
} }
}
Output: 3.14159 Output: error

final keyword at method level


A. When final keyword used with method defined in base class , then its sub classes
cannot override this method.
B. the compiler checks and gives an error if you try to override the method.
class Employee class FinalDemo
{ {
final void show() public static void main(String args[])
{ {
System.out.println("Hello");
Developer d=new Developer();
}
d.show();
}
class Developer extends Employee }
{ }
void show()
{

29
30

System.out.println("Hai"); Output:
} error
}

final keyword at class level


1. when a class is defined with final keyword then the class cannot be used to
derive a new class.(subclass cannot be created)
2. when we want to restrict inheritance then make class as a final.

Example:

public final class A


{
......
......
}
public class B extends A
{
// it gives an error, because we can not inherit final class
}

example of final keyword at class level


final class employee
{
int salary=10000;
}
class developer extends employee // it gives an error
{
void show()
{
system.out.println("hello");
}
}

class finaldemo
{
public static void main(string args[])
{
developer d=new developer();
d.show();
}
}

output:

30
31

error

Abstract class
1.The abstract keyword is a non-access modifier, used for classes and methods.

2. abstract class

A. it is a restricted class that cannot be used to create objects (to access it, it must be
inherited from another class).
B. It cannot be instantiated.
C. It needs to be extended.
3.abstract method

A.It is a method that can only be used in an abstract class, and it does not have a body.
B.The body is provided by the subclass and its method should be implemented.
C.Abstraction is a process of hiding the implementation details and showing only
functionality to the user.
D.It can have final methods which will force the subclass not to change the body of the method.

abstract class Bank class TestBank


{ {
abstract int Interest(); public static void main(String args[])
} {
Bank b =new SBI();
class SBI extends Bank System.out.println("Rate of Interest is: "+b.Interest());
{
int Interest() Bank b=new ANDHRA();
{ System.out.println("Rate of Interest is: "+b.Interest());
return 7; }
} }
}

Output:
class ANDHRA extends Bank Rate of Interest is: 7
Rate of Interest is: 8

31
32

{
Int Interest()
{
return 8;
}
}

Interfaces

1. An interface is a blueprint of a class. Program to show interface


2. It has static constants and abstract
methods. interface Bank
3. There can be only abstract methods {
in the interface, not method body. float interest();
4. It is used to achieve abstraction and }
multiple inheritance in Java.
5. Java Interface also represents the IS- class SBI implements Bank
A relationship. {
6. It cannot be instantiated just like the public float interest()
abstract class.
{
Reasons to use interface in java
return 9.15f;
1. It is used to achieve abstraction.
}
2. By interface, we can support the
}
functionality of multiple inheritance.
How to declare an interface?
1. An interface is declared by using the class Andhra implements Bank
interface keyword. {
2. It provides total abstraction; means public float interest()
all the methods in an interface are {
declared with the empty body, and return 9.7f;
all the fields are public, static and }
final by default. }
3. A class that implements an interface
must implement all the methods class Inter
declared in the interface. {
Syntax: public static void main(String[] args)
interface interfacename {
Bank b=new SBI();
{
s.o.p("rate of interest "+b.interest());
constant fields
methods that abstract by default. Bank b=new andhra();
} s.o.p ("Rate of Interest is: "+b.Interest());

32
33

a class extends another class, an


interface extends another interface, but
a class implements an interface.

Multiple inheritance in Java by interface


1. The process of deriving one derived class from several base classes is known as
multiple inheritance.
2. Java doesnot directly support multiple inheritance through classes due to the
complexity.
3. It is implemented through interfaces.
4. If a class implements multiple interfaces, or an interface extends multiple interfaces,
then it is a multiple inheritance.
Program to show multiple inheritance
interface Printable
{
void print();
}
interface Showable
{
void show();
}
class Mtest implements Printable , Showable
{
public void print()
{
System.out.println("Hello");
}
public void show()
{
System.out.println("Welcome");
}

33
34

public static void main(String args[])


{
Test t=new Test();
T.print();
T.show();
}
}

Output:
D:\java>javac Mtest.java
D:\>java>java Mtest.java
Hello
Welcome

Difference between abstract class and interface

Abstract class Interface


1) Abstract class can have abstract and non- Interface can have only abstract methods.
abstract methods.
2) Abstract class doesn't support multiple Interface supports multiple inheritance.
inheritance.
3) Abstract class can have final, non-final, Interface has only static and final variables.
static and non-static variables.
4) Abstract class can provide the Interface can't provide the implementation
implementation of interface. of abstract class.
5) The abstract keyword is used to declare The interface keyword is used to declare
abstract class. interface.
6) An abstract classcan extend another Java An interface can extend another Java
class and implement multiple Java interface only.
interfaces.
7) An abstract classcan be extended using An interface classcan be implemented
keyword "extends". using keyword "implements".
8) A abstract class can have class members Members of a interface are public by
like private, protected, etc. default.
abstract class Bank interface Printable
{ {
abstract int Interest(); void print();
} }
class SBI extends Bank interface Showable
{ {
int Interest() void show();
{ }
return 7; class Test implements Printable,Showable
} {
} public void print()

34
35

class ANDHRA extends Bank {


{ System.out.println("Hello");
Int Interest() }
{ public void show()
return 8; {
} System.out.println("Welcome");
} }

Java Package
A java package is a group of similar types of classes, interfaces and sub-packages.
There are two types: 1. built-in package 2. user-defined package.
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.

Built-in Packages
1.The Java API is a library of prewritten classes, included in the Java Development
Environment.
2.The library is divided into packages and classes.
3.you can either import a single class (along with its methods and attributes), or a whole
package that contain all the classes
4.To use a class or a package from the library, the import keyword is used
Syntax
// Import a single class // Import the whole package

import package.name.Class; import package.name.*;


import java.util.*;
import java.util.Scanner;
import java.lang.*;
import java.lang.math;
import java.lang.string;
import java.awt.color;

Naming conventions
Naming conventions
java.lang.Math.sqrt(x);

35
36

java-> package name


lang-> subpackage name
Math-> classname
sqrt(x)-> methodname

There are many built-in packages such as


java, lang, awt, javax, swing, net, io, util, sql
etc.

User-defined-package
Java package created by user to categorized classes and interface.
The package keyword is used to create a package in java.
creating packages:
steps:
1.create the package at the beginning of a file using package keywyord
package packagename;
2. define the class that is to be use package and declare it public
3.create subdirectory under the directory where the main source file are stored
4. name the file as classname.java
5. compile the file. This creates .class file in the package directory.
d:\>md mypack;
d:\>cd mypack;
Step1: Step 2 :
open notepad , type , save file as open notepad , type , save file as
Test.java in mypack folder Packtest.java in java folder

package message; import message.*;


class PackTest
public class Test {
{ public static void main(String args[])
public void msg() {
{ Test t=new Test();
System.out.println(“hello”); t.msg();
} }
}

36
37

}
Save the program as Sample.java
Compile and run the program

D:\>javac Packtest.java
D:\>java Packtest
Hello

II. accessing package in other files


import packagename.classname; or import packagename.*;
or import packagename1.package2.classname;

37

You might also like