Datascience IV Java Unit 1, 2
Datascience IV Java Unit 1, 2
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
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
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
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
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:
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)
boolean false 1 bit true and false boolean status = false true or false
8
9
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
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");
}
}
}
11
12
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
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
14
15
15
16
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");
}
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
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;
20
21
this keyword
In java, this is a keyword and a reference variable that refers to the current object.
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
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
23
24
445
Note : java program to show matrix multiplication compulsory
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
Multiple Inheritance:
1. The process of deriving one
derived class from several base
classes is known as multiple
inheritance
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
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).
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
29
30
System.out.println("Hai"); Output:
} error
}
Example:
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.
Output:
class ANDHRA extends Bank Rate of Interest is: 7
Rate of Interest is: 8
31
32
{
Int Interest()
{
return 8;
}
}
Interfaces
32
33
33
34
Output:
D:\java>javac Mtest.java
D:\>java>java Mtest.java
Hello
Welcome
34
35
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
Naming conventions
Naming conventions
java.lang.Math.sqrt(x);
35
36
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
36
37
}
Save the program as Sample.java
Compile and run the program
D:\>javac Packtest.java
D:\>java Packtest
Hello
37