Unit 1 Java
Unit 1 Java
(BCA 512)
By
Anuj Kumar Raghav
(TMU07531)
Unit 1
Introduction of Java
1. Object Oriented
Java is an object oriented programming language which follows the concepts of oop’s.
2. Platform Independent
Java application programs written on one operating system can be able to run on any
platform. So the java is platform independent. On compilation java program is compiled
into byte code (.class file). This byte code is platform independent and can be run on any
machine.
3. Simple
Java syntax is similar to c and c++ and it follow the oop’s concepts so it is easy to learn.
4. Secure
Java’s securing feature it enable to develop virus free, tamper free (software which is not
modify by attacker). Authentication techniques are based on public key encryption
Architectural Neutral
5. Portable
We may carry the java byte code to any platform.
6. Robust
Robust simply means strong. Java uses strong memory management. There is lack of
pointers that avoids security problem. There is automatic garbage collection in java.
There is exception handling and type checking mechanism in java. All these points make
java robust.
7. Multi Threaded
A thread is like a separate program, executing concurrently. We can write Java programs
that deal with many tasks at once by defining multiple threads. The main advantage of
multi-threading is that it doesn't occupy memory for each thread. It shares a common
memory area. Threads are important for multi-media, Web applications etc.
8. Interpreted
Java is a compiled programming language, but rather than compile straight to executable
machine code, it compiles to an intermediate binary form called JVM byte code. The byte
code is then compiled and/or interpreted to run the program.
9. High Performance
Java is faster than traditional interpretation since byte code is "close" to native code still
somewhat slower than a compiled language (e.g., C++)
Types of java Application
1. Web Application
Java is used to create server side applications. Currently, servlet, jsp, struts, jsf etc.
technology are used.
2. Stand- Alone Application
It is also known as desktop application or window based application. An application
that we need to install on every machine such as antivirus, media player etc. AWT and
Swing is used in java for creating standalone application.
3. Enterprise Application
An application that is distributed in nature, such as banking application etc. In java
EJB is used to create enterprise application.
4. Mobile application
Java is used to create application software for mobile devices. Currently
java ME is used for creating application for small devices and java is programming for
Google Android application development.
Java is freely available on the oracle website Download the latest version of JDK(java
Development Kit)on your machine.
Install JDK on your machine.
Once you have installed java on your machine it need to set environment variable to point
to correct installation directory.
An environment variable is a dynamic “object ” on a computer that stores a value (like a key
value ), which can be reference by one or more software programs in Windows. Like in java ,
we will set environment variable with name ”java” and its values will be the path of /bin
directory present variable which will give it the path to the execution.
Step:4 Now alter the path variable so that it also contains the path to jdk installed
directory.
First java Program
}
class: class is a keyword is used to declare classes in java
public: It is an access specifiers . Public means this function is visible to all.
static: static is used to make a function static. To execute a static function you
do not have to create an Object of the class. The main () method here is called
by jvm, without creating any object for class.
void: void is return type, meaning this function will not return anything.
main(): main() method is the most important method in a java program . this
is the method which is executed hence all logic must be inside the main()
method. If a java class is not having a main() method, it causes compilation
error.
System.out.println(): This is used to print anything on the consol like
printf()in c.
Step: 1 Open a text editor like Notepad and write the code as above.
Step: 2 save the file as FirstJava.java
Step: 3Open command prompt and go to the directory where you saved your first java
program
Step: 4 Type javac FirstJava.java then enter to compile the program
Step: 5 Now Type java FirstJava on command prompt the enter to run program.
Step: 6 Now you will be able to see Welcome in Aims oriented on your command
prompt.
Java Development Kit (JDK)
float
Float data type is a single-precision 32-bit IEEE 754 floating point
double
double data type is a double-precision 64-bit IEEE 754 floating point
boolean
boolean data type represents one bit of information
There are only two possible values: true and false
char
char data type is a single 16-bit Unicode character
Byte Code:
When the java program compile the source code is converted in intermediate code with
extension .class called, Byte Code which is read by the JVM machine.
Byte code and JVM both makes java platform independent.
Tokens
1. Keywords
2. Identifiers
Identifiers are the name given to various programming element like variable name, class
name, object name array name, function name interface name, package name.
Rules for constructing identifier name
All the identifiers must start with either a letter (a to z or A to z) or currency
character ($) or an underscore.
They can have alphabets, digits, and the underscore (_) and dollar sign ($)
characters.
They must not begin with a digit.
Identifiers in java are case sensitive abc and ABC are two different identifiers.
Uppercase and lowercase are distinct.
Naming conventions
1. When more than one word are used in a public methods and instance name, the
second and subsequent words are marked with a leading letters.
Examples: dayTemperature, firstDayOfMonth, totalMarks
2. All private and local variable use only lowercase letters combine with
underscores.
Examples: length, batch_strength
3. All classes and interface start with uppercase letter(and each subsequent word
with a leading uppercase)
Example: Student, HelloJava, Vehical, MotorCycle
4. Variables that represent constant values use all uppercase letter and
underscore between words.
Example: TOTAL, F_MAX, PRINCIPAL_AMOUNT
5. Package name should be in lowercase
Example: java, lang, sql, util, etc.
6. Method name should be in lowercase letters.
Example: print (), println().
3. Operator
Operator is the special symbols the perform the mathematical and logical manipulation.
Types of operator
1. Arithmetic operator
Operator Meaning
+ Addition
- Subtraction
* Multiplication
/ Division
% Modulus
2. Relational operator
3. Logical operator
Operator Meaning
& Bitwise AND
| Bitwise OR
^ Bitwise XOR
~ One ‘Complement
>> Bitwise right shift
<< Bitwise left Shift
1. Ternary operator
Operator that performs operation on three operands called ternary operator.
Conditional Operator
The conditional operator? : is called ternary operator as it requires three
operands.
Syntax:
Conditional Exp? Exp1: Exp2
If the value of conditional expression is true then the exp1 is evaluated, otherwise exp2 is
evaluated.
2. Assignment operator
Operator ('=') which is used for assigning a value to a variable is called assignment
operator. This operator takes the expression on its right-hand-side and places it into
the variable on its left-hand-side.
For example: m = 5;
1. Increment Operator
++ Operator increment the value of a variable by 1 is called increment operator.
Pre-increment
++ is written before variable name. Value is incremented first then
incremented value is used in expression.
Ex:
public class IncPre
{
public static void main(String args[]) {
int i, a=5;
i=++a;
System.out.println(i);
}
}OUTPUT: 6
Post-increment
++ is written after variable name. Value is assigned to expression after that the
value is increment.
Ex:
public class IncPre
{
public static void main(String args[]) {
int i, a=5;
i=a++;
System.out.println(i);
}
}OUTPUT:5
2. Decrement Operator
-- Operator decrement the value of a variable by 1 is called decrement operator.
Pre-decrement
-- is written before variable name. Value is decremented first then
decremented value is used in expression.
Ex:
public class IncPre
{
public static void main(String args[]) {
int i, a=5;
i=--a;
System.out.println(i);
}
}OUTPUT: 4
Post-decrement
-- is written after variable name. Value is assigned in expression then the
decrement the value.
Ex:
public class IncPre
{
public static void main(String args[]) {
int i, a=5;
i=a--;
System.out.println(i);
}
}OUTPUT:5
4. Separator
The separators define the structure of a program. The separators are used parentheses (
), braces { }, the period (.) and (;) semicolon.
Comments
Comments are special part of the program, to describe or explain the code which make
easy to understand.
Comments are those lines which are not read by the compilers.
Types of Comments
1. Single line comments
Single line comments starts with two forward slash (//)
It useful when only single lines are commented.
final int a=5// a is constants variable
2. Multiline comments
Multiline comments are starts with forward slash/ and after that star (*) and
the text or comment line put then again star(*) put the again forward slash(/)
put to comment .
It is useful when we comment multiple line in program.
1) If Statement:
Simple if statement
if-else statement
if-else-if ladder
Nested if-statement
1) Simple if statement:
Syntax
if(condition) {
statement 1; //executes when condition is true
}
2) if-else statement
Syntax:
if(condition) {
statement 1; //executes when condition is true
}
else{
statement 2; //executes when condition is false
}
3) if-else-if ladder:
Syntax
if(condition 1) {
statement 1; //executes when condition 1 is true
}
else if(condition 2) {
statement 2; //executes when condition 2 is true
}
else {
statement 2; //executes when all the conditions are false
}
4. Nested if-statement
Syntax
if(condition 1) {
statement 1; //executes when condition 1 is true
if(condition 2) {
statement 2; //executes when condition 2 is true
}
else{
statement 2; //executes when condition 2 is false
}
}
Switch Statement:
switch (expression){
case value1:
statement1;
break;
.
.
.
case valueN:
statementN;
break;
default:
default statement;
}
Consider the following example to understand the flow of the switch statement.
Student.java
Loop Statements
for loop
while loop
do-while loop
for loop
while loop
while(condition){
//looping statements
}
0
2
4
6
8
10
do-while loop
do
{
//statements
} while (condition);
Jump Statements
break statement
The break statement cannot be used independently in the Java program, i.e., it can only be written inside the
loop or switch statement.
0
1
2
3
4
5
6
continue statement
Consider the following example to understand the functioning of the continue statement in Java.
if(j == 4) {
continue;
}
System.out.println(j);
} }}}
Output:
0
1
2
3
5
1
2
3
5
2
3
5
Arrays:-
Array is a final class inheritance is not possible.
Arrays are used to store the multiple numbers of elements of single type.
The length of the array is established at the time of array creation. After creation the length is fixed.
int[] a;
int []a;
int a[];
class Test
{
public static void main(String[] args)
{
int[] a={10,20,30,40};
System.out.println(a[0]);
System.out.println(a[1]);
System.out.println(a[2]);
System.out.println(a[3]);
}
}
class Test
{
public static void main(String[] args)
{
int[] a={10,20,30,40};
for (int i=0;i<a.length;i++)
{
System.out.println(a[i]);
}
}
}
Ex:-
class Test
{
public static void main(String[] args)
{
int[][] a={{10,20,30},{40,50,60}};
System.out.println(a[0][0]);//10
System.out.println(a[1][0]);//40
System.out.println(a[1][1]);//50
}
}
OOP’s Concepts
Object means a real word entity such as pen, chair, table etc. Object-Oriented Programming
is a methodology or paradigm to design a program using classes and objects. It simplifies the
software development and maintenance by providing some concepts:
Object
Class
Inheritance
Abstraction
Encapsulation
Polymorphism
Class
Object
Objects are the basic unit of OOP. They are instances of class, which have data
members and use various member functions to perform tasks.
Object is the basic unit of object-oriented programming. Objects are identified by its
unique name. An object represents a particular instance of a class.
Class
“Class is a user defined data types, which holds variables and, which can be accessed and
used by creating instance of that class.”
Class is just a blue print, which declare and defined variables and methods. All objects
of this class will share these data member and function.
About Class:
1. Class name start with an uppercase letter. If class name is made then one word, the
first letter of each word must be in uppercase.
Ex: - Class Study, class AimsTutorial
2. Objects of the class holds separate copies of data member. We can create as many
objects of a class as we need.
How to declare class:
Syntax:
public class Class_Name
{
variables;
methods( );
public static void main(String[] args)
{
Class_Name obj=new Class_Name ()
}
};
Example:
public class Aims
{
int i=10;
public static void main(String[] args)
{
Aims a1=new Aims ();
System.out.println (a1.i);
}
}
Output: 10;
Objects
Objects are the variable which declare using class name, it holds the data variable, declared in
the class and the member function works on these class objects.
Local variables − Variables which 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.
class Test
{
public static void main(String[] args)
{
int a=10; Local variables
int b=20;
System.out.println(a+b);
}
}
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 Test
{
int a=10;
int b=20;
void add()
{
System.out.println (a+b);
}
public static void main(String[] args)
{
Test t=new Test();
System.out.println(t.a+t.b);
t.add();
}
}
Methods (behaviors):-
1) Methods are used to provide the business logic of the project.
2) The methods like a functions in C-language called functions, in java language is called
methods.
3) Inside the class it is possible to declare any number of methods based on the developer
requirement.
4) As a software developer while writing method we have to fallow the coding standards like
the method name starts with lower case letters if the method contains two words every inner
word also starts uppercase letter.
5) It will improve the reusability of the code. By using methods we can optimize the code.
Syntax:-
[modifiers-list] return-Type Method-name (parameter-list)throws Exception
Ex:-
public void m1()
public void m2(int a, int b)
Method Signature:-
The name of the method and parameter list is called Method Signature. Return type and
modifiers list not part of a method signature.
Ex:- m1(int a,int b)------Method Signature
m2(); ------------------Method signature
There are two types of methods:-
Instance method
Method which are declare and defined inside a class and without static keyword and
called using object.
class Test
{
void display()
{
System.out.println("Aims Tutorial");
}
}
}
Static method
Method which are declare and defined inside a class and with static keyword and
called using classname.
class Test
{
Static void display ()
{
System.out.println ("Aims Tutorial");
}
Test.display ();
}
}
Constructor
Constructor is a special type of method which has same as class that is used to initialize the
object. Constructor is called at the time of object creation. It constructs the value or provides
data for the object that is why it is known as constructor.
2. Parameterized constructor.
A Constructor that has parameter is known as parameterized
constructor.
Why use parameterized Constructor
parameterized constructor provide the different values to the
distinct object
class Square
{
public static void main(String args[])
{
Square b=new Square (5);
}
Square(int n)
{
System.out.println(n*n);
}
}
this heyword:-
This keyword is used to represent
1. Current class variables.
2. Current class methods.
3. Current class constructors.
class Test
{
int a=10;
int b=20;
void add(int a,int b)
{
System.out.println(a+b);
System.out.println(this.a+this.b);
}
public static void main(String[] args)
{
Test t=new Test();
t.add(100,200);
}
}
POLYMORPHISM
1) One thing can exhibits more than one form called polymorphism.
2) The ability to appear in more forms.
3) Polymorphism is a Greek word poly means many and morphism means forms.
Types of Polymorphism
1. Compile Time Polymorphism (Early binding, Static binding)
2. Run Time Polymorphism (Late binding, Dynamic binding)
Ex:-Method Overloading Ex:-Method Overriding
{
System.out.prinln(a+b);
}
public static void main(String args[])
{
Cal C1=new Cal();
C1.add(2,4);
C1.add(2.5f,3.4f);
}
}
B. Method Overriding
If we inherit a class into the derived class and provide a definition for one of the
base class’s method again. The method is said to be overriding.
Requirement for method overriding
Inheritance should be there. method overriding cannot be done within a class, for
this we require a derived class and a base class.
method signature should be same in base class and derived class.
class Base
{
void show()
{
System.out.prinln(“Base Class”+”\t");
}
}
void show()
{
System.out.prinln("Derived Class");
}
public static void main(String[]args)
{
Base B=new Base();
Derived D=new Derived();
B.show();
D.show();
}
}
Output:
Base Class
Derived Class
In the above example, we are calling the overridden function using Base Class and Derived
Class object. Base class object call base class version of function and derived class’s object
call Derived class version of function.
Method overloading is the example of compile time Method overriding is the example of
4)
polymorphism. run time polymorphism.
In java, method overloading can't be performed by
changing return type of the method only. Return type Return type must be same or covariant
5)
can be same or different in method overloading. But you in method overriding.
must have to change the parameter.
ABSTRACTION
Hiding the internal implementation details and highlighting the essential functionality to the
user this mechanism is called abstraction.
Ex:
a. Bank ATM Screens (Hiding thee internal implementation and highlighting set of services
like withdraw, money transfer, mobile registration).
b. Mobile phones (The mobile persons are hiding the internal circuit implementation and
highlighting touch screen).
Abstraction concepts are implemented in java by abstract class and interface
1. Abstract Class
Abstract class is a java class which contains at least one abstract method.
To specify the particular class is abstract and particular method is abstract method by
using abstract modifier.
For the abstract classes it is not possible to create an object. Because it contains the
unimplemented methods.
For any class if we don’t want instantiation then we have to declare that class as abstract
i.e., for abstract classes instantiation (creation of object) is not possible.
abstract class Test
{
Abstract class:-
class Test
{
abstract void m1();
abstract void m2();
abstract void m3();
}
abstract class Add
{
abstract void add(int a, int b);
}
class Cal extends Add
{
void add(int a, int b)
{
System.out.println(a+b);
}
public static void main(String[] args)
{
Cal C1=new Cal();
C1.add(3,4);
}
}
Abstract methods:-
The method which is having declaration but not implementations such type of methods are
called abstract Method. Hence every abstract method should end with “;”.
The child classes are responsible to provide implementation for parent class abstract
methods.
public abstract Add
{
abstract void add(int a, int b);//it is abstract method which has no definition
}
class Cal
{
void add(int a, int b)
{
System.out.println(a+b);
}
public static void main(String[] args)
{
Cal C1=new Cal();
C1.add(3,4);
}
}
2. Interface
1. Interface is also one of the type of class it contains only abstract methods.
2. For the interfaces also .class files will be generated.
3. Each and every interface by default abstract hence it is not possible to create an
object.
4. Interfaces not alternative for abstract class it is extension for abstract classes.
5. 100 % pure abstract class is called interface.
6. The Interface contains only abstract methods means unimplemented methods.
7. Interfaces giving the information about the functionalities it are not giving the
information about internal implementation.
8. To provide implementation for abstract methods we have to take separate class that
class we can called it as implementation class for that interface.
9. Interface can be implemented by using implements keyword.
10. For the interfaces also the inheritance concept is applicable.
Syntax:-
Interface interface-name
Ex:- interface it1
Note: -
if we are declaring or not By default interface methods are public abstract
interface it1 abstract interface it1
{ {
Void m1(); Both are same public abstract void m1();
Void m2(); public abstract void m2();
} }
interface Cal
{
void add(int a, int b);
void sub(int a, int b);
}
class Solution implements Cal
{
void add(int a, int b)
{
System.out.prinln(a+b);
}
void sub(int a, int b)
{
System.out.prinln(a-b);
}
public static void main(String[] args)
{
Solution S1=new Solution()’
S1.add();
S1.sub();
}
Encapsulation
The process of binding the data and code as a single unit is called encapsulation.
Encapsulation in Java is a process of wrapping code and data together into a single unit, for example, a
capsule which is mixed of several medicines.
We are able to provide more encapsulations by taking the private data(variables) members.
To get and set the values from private members use getters and setters to set the data and to
get the data.
But in Java, the programmer need not care for all those objects which are no longer in use.
Garbage collector destroys these objects. The main objective of Garbage Collector is to free
heap memory by destroying unreachable objects.
Syntax:
1. Call-by-value
2. Call-by-reference.
Call-by-value
In case of call by value original value is not changed. Let's take a simple example:
1. class Operation{
2. int data=50;
3.
4. void change(int data){
5. data=data+100;//changes will be in the local variable only
6. }
7.
8. public static void main(String args[]){
9. Operation op=new Operation();
10.
11. System.out.println("before change "+op.data);
12. op.change(500);
13. System.out.println("after change "+op.data);
14.
15. }
16. }
Output:before change 50
after change 50
Call-by-reference
public class A{
int d=50;
public void add(int d){
d=d+100;//These changes will happen locally, that means it will be reflected only in this function
System.out.println("The value in function after performing addition is " + d);
}
public static void main(String args[]){
A obj=new A();
System.out.println("before change "+obj.d);
obj.add(500);
System.out.println("after change "+obj.d);
}
}
The java command-line argument is an argument i.e. passed at the time of running the java program.
import java.util.Scanner;
// Driver Class
public class ScannerDemo1 {
// main function
public static void main(String[] args)
{
// Declare the object and initialize with
// predefined standard input object
Scanner sc = new Scanner(System.in);
// String input
String name = sc.nextLine();
// Character input
char gender = sc.next().charAt(0);
Input
Geek
F
40
9876543210
9.9
Output
Name: Geek
Gender: F
Age: 40
Mobile Number: 9876543210
CGPA: 9.9