Sunteți pe pagina 1din 63

Welcome to Semester IV

Java Programming
Theory exam Marks 80-20
Practical exam Marks 50-25
Term work Marks 25
Unit I
Java Fundamentals
History of Java, Features of Java, Object oriented
concepts related to java,

Java environment and tools


Garbage collection and finalize method,

Data types, variable, expressions, operators, and


control structures, arrays, string and mutable
string.
Introduction to Java

Java was developed by James Gosling at Sun Microsystems in


1991.

It took 18 months to develop the first working version.


This language was initially called Oak but was renamed Java in
1995.

The primary motivation was the need for a platform-independent


(that is, architecture-neutral) language that could be used to create
software to be embedded in various consumer electronic devices.
Java Applets and Applications

An application is a program that runs on your computer, under the


operating system of that computer.
That is, an application created by Java is more or less like one
created using C or C++.

An applet is an application designed to be transmitted over the


Internet and executed by a Java-compatible Web browser.

An applet is a program that can react to user input and dynamically


change.
Javas Magic: The Bytecode
The key that allows Java to solve both the security and the
portability problems is that the output of a Java compiler is not a
executable code. Rather, it is bytecode.

Bytecode is a highly optimized set of instructions designed to be


executed by the Java run-time system, which is called the Java
Virtual Machine (JVM).
That is, the JVM is an interpreter for bytecode.

Translating a Java program into bytecode helps makes it much


easier to run a program in a wide variety of environments.
The reason is straightforward: only the JVM needs to be
implemented for each platform.
Features of Java

Simple , Small & familiar


Compiled & Interpreted
Platform Independent & Portable
Object-oriented
Robust & Secure
Distributed
Multithreaded & Interactive
High performance
Dynamic
Monitoring & Manageability
Simple , Small & familiar

Java was designed to be easy for the professional programmer to


learn and use effectively.

If you already understand the basic concepts of object-oriented


programming, learning Java will be even easier.

Java inherits the C/C++ syntax and many of the object-oriented


features of C++
Compiled & Interpreted

Usually a computer language is either compiled or interpreted


Java combines both these approaches

Java compiler translates source code into byte code


(machine independent code byte code )

Java Interpreter generates machine code that can be directly


executed by the machine that is running the java program

(machine dependant code Out put )


Platform Independent & Portable

Java programs can be easily moved from one computer to another


anywhere and anytime

Changes and upgrades in OS , processors and system resources will


not force any changes in java program

Eg: download any java applet from a remote computer through


Internet on your local computer and execute it locally on your
computer

Portability :
1. Java compiler generates byte code that can be implemented on
any machine
2. Size of the primitive data types are machine independent
Object-oriented
Almost everything in java is an Object
Object has data or state (instance variables)and behavior (methods)

Robust & Secure


Java is a robust language , it provides many safeguard to ensure
reliable code
It has strict compile time and runtime checking for data types
and manages all memory related problems

Java also incorporates the concept of exception handling which


captures errors and handles exceptions

Security
Security becomes important issue for a language that is used for
programming on Internet

Threats of viruses
Distributed

Java is distributed language for creating applications on networks

The applications can open and access remote objects on Internet as


easy as they can do in a local system

Multithreaded & Interactive

Multithreaded means handling multiple tasks simultaneously


User need not wait for finishing the 1st task before starting the 2nd
task

High performance

Due to the use of byte code


Object Oriented Programming Concepts

Encapsulation
Wrapping up of data and methods into a single unit is known as
encapsulation
The data can be accessed only through the methods which are wrapped in
the class

Abstraction refers to the act of representing essential features without


including the background details or explanations

Inheritance
Inheritance is the process by which object of one class acquire the
properties of objects of another class

The concept of inheritance provides the idea of reusability


Each subclass has his own unique features and derived features of its
parent class
Polymorphism

This means ability to take more than one form

Message Communication

Objects communicates with one another by sending and receiving


information
A message for a an object is a request for execution of a procedure and
therefore it invokes a method in the receiving object that generates the
desired result

Eg :
Employee objEmployee;
objEmployee = new Employee();
OR
Employee objEmployee = new Employee();
objEmployee.cal_salary();
Java Program Structure

Documentation Section
This section comprises a set of comment lines giving the name of
the program , the author and other details

Package Statement
The first statement allowed in java file is a package statement

Import Statement
This is similar to the #include statement in c, c++

Interface Statement
An interface is like a class , generally used to implement multiple
inheritance
Class Definition
Java programs may contain multiple class definitions
Classes are the primary and essential elements of java program

Main method class


Every java stand alone program require a main method as it is a starting point of a
program

Main method always written within the class

Public : access specifier that declares the main method as unprotected and
therefore making it accessible to all other classes

Static : this method as one that belongs to the entire class and not a part of any
object of the class

This method is static because interpreter calls this method before creating any
objects

void : main() doesnt return any value

String args[] : command line argument are held in this array


//Lets see a simple java program Single line Comment

public class HelloWorld

/*The execution will start from here */ Multi line comment


Entry point for your
application
{
public static void main (String args[])
{
System.out.println("Hello World !!!!");

} // end of main() Prints Hello World !!!

}//end of class

Type all code commands and file names exactly as shown , Java is
highly case sensitive
Java Tokens :
Reserved key words
Eg: abstract, continue , goto, package , this, super, throw, try, static ,
switch , final, finally etc

Identifiers
They are programmer designed tokens

Identifiers are names of variable , methods, classes packages and


interface

Rules: Can have alphabets , digits, underscore and dollar

Must not begin with digit

Use Uppercase and lowercase


It should be meaningful, short enough to be quickly and easily
typed and read
Literals
They are sequence of characters that represent constant values to
be stored in variable
Integer (1,2,3)
Floating point (123.65)
Character (a)
String (hello)
Boolean (true , false)

Operators
Arithmetic, relational , bitwise , Shift , Conditional
(+,+=), (<,<=), (|, ^=) , (>>,<<) , (? :)

Separators
These are the symbols used to indicate where group of code are
divided and arranged
Eg: ( (), {}, [], ;, , , :, . )
Integer Data Types

Type Bits
Byte 8 -127 128
short 16 -32768 32767
int 32 -2,147,483,648..+7
long 64 -9,223,372,036,854,775,808..+7

Floating Point

Type Bits Range Precision


(decimal digits) (decimal digits)
float 32 38 7
double 64 308 15
Characters

A char value stores a single character from the Unicode character set
A character set is an ordered list of characters
A, B, C, , a, b, ,0, 1, , $,

The char type assumes a size of 2 bytes but basically it holds only a
single character

Boolean
A boolean value represents a true/false condition.

LD2\Conversion.java
class Student
{
String name=XYZ";
int roll_no;

void getData()
{
System.out.println ("Name is"+name);

}
}

class Display

{
public static void main (String args[])
{
Student objStudent = new Student();
objStudent.getData();

}
interface

interface Student
{
int getRollNum(int roll_no);
}

class Subclass implements Student


{
public int getRollNum(int roll_no)
{
return(roll_no);
}

}
class MyInterface

{ public static void main(String args[])


{
Subclass objSubclass = new Subclass() ;

System.out.println("Roll No"+ objSubclass.getRollNum(4101));


}}
Arrays
Declaration of array

type arrayname [ ]; OR type [ ] arrayname ;

int number[ ]; OR int [ ] number;

Creation
int number [ ] = new int[5]; OR int number [ ] ;
number= new int [5];

Initialization
int number [ ] = {1, 2 ,3 ,4 ,5};

Array length

int size = number.length;


Two Dimensional Array

int number [row] [column];

int number [ ] [ ] ; int number [ ] [ ] = new int [3][3];


number = new int [3][3]; OR

Eg:

int table [ ] [ ]= {

{0, 0, 0,},
{1, 1, 1 },
{2, 2, 2 }
};

OR

int table [ ] [ ]= {{0, 0, 0,}, {1, 1, 1 }, {2, 2, 2 }};


Variables

1. It tells compiler what the variable name is


2. It specifies what type of data the variable will hold
3. Place of declaration to decide the scope of the variable

The syntax of a variable declaration is


data-type variable-name;

Multiple variables can be declared on the same line


int total;
long total, count, sum;

Variables can be initialized (given an initial value) in the declaration


int total = 0, count = 20; Assignment Statement
double unitPrice = 57.25;

Using a read statement


LD2\Reading.java
Java variables are classified into three types

1. Instance variables //every object has its own personal copy of an instance
variable
2. Class variables //Class variables only have one copy that is shared by all the
different objects of a class
3. Local variables
Instance and class variables are declared inside a class, Instance variables are
created when the objects are instantiated and they are associated with the
objects

{
int x=10;
{
int y=5;
}

{
int z=4;
}

}
Constants

Constant is a variable whose value cannot be changed


Constants can be declared using final keyword
All constants must be initialized

E. g.
final int x=10;
final double PI= 3.14

Advantages:
readability Constant declaration helps to improve the
readability of the program
efficiency It improves the efficiency as changing the value
becomes very easy
error detection Error detection becomes very easy
Arithmetic Expressions

Is a combination of variables ,constants and operators arranged as


per the syntax of the language

Algebraic expression Java Expression


ab-c a*b-c

(m+n) (x+y) (m+n) *(x+y)

ab/c a*b/c

x/y+c x/y+c

2x+1 2*x+1
LD2\Expressions.java
Operators

1.Arithmatic Operators
(+ - * / %)
2.Relational Operators
(< > <= >= == !=)
3.Logical Operators
(&& || !)
4.Assignment Operator
(=)
5.Incremental & Detrimental Operator
(++m,--m)
6.Conditional Operator
(a>b ? a: b)
7.Bitwise Operator
(<< >> >>> ` )
8.Special Operator
(. )
Control Structures

Use Control flow statement to :

Conditionally execute statements


Repeatedly execute a block of statements
Change the normal , sequential flow of control

Categorized into two types:

Selection statements
Iteration statements
Control Statements

If

If else

If else
else if
else if
.
.
default

while, do while , for

switch case , break continue


Selection Statements

Allows programs to choose between alternate action on


execution

if Used for conditional branch

if (condition)
{
statement 1;
}
else
{
statement 2;
}
switch used as an alternative to multiple if blocks

switch (expression)
{
case value1: //statement sequence
break;

case value2: //statement sequence


break;

default: // default statement sequence


}
if statement

if the condition is true then statement

if (some Boolean expression)


{
statements to be executed if true
}

Eg :
If else statement

if (some Boolean expression)


{
statements to be executed if true
}
else
{
statements to be executed if false
}
Else if ladder

if (some Boolean expression)


{...}
else if (another Boolean expression)
{...}
else { . . . }
Switch Case
In java switch is a multi way branch statement .It provides as easy way
to dispatch execution to different parts of your code bases on the value
of an expression

It is a better alternative than a large series of if-else-if statements

switch (expression) {
case Constant1: // Do following if expression==Constant1
Bunch of Stuff
break;
case Constant2: // Do following if expression==Constant2
Bunch of Stuff
break;
default: // Do the following otherwise
Bunch of Stuff
break;
}
LD3\DemoSwitch.java
Iteration Statements

Allow a block of statements to execute repeatedly

While loop

Enter the loop if the condition is true

while ( condition )
{
Body of the loop
}

LD3\SampleWhile.java
do while loop

Loop will execute at least one time even if the condition is false

do
{

Body of the loop

}
while ( condition )

LD3\DemoDoWhile.java
for loop
When the for loop first starts the initialization portion of the loop is
executed , which sets the value of the loop control variable which acts
as a counter that controls the loop
The initialization expression is executed only once

Condition evaluation , it usually tests the loop control variable against


a target value ,if the expression is true then the body of the loop is
executed, else terminate

The incremental portion or detrimental portion of the loop control


variable , this process repeats until the controlling expression is false

for (declaration1 ; booleanExpression ; expressionList2)


{
Body of the loop
}
LD3\DemoFor.java
Labeled loops

We can give a label to a block of statements.


A label just place it before loop with colon at the end

label : for ( conditions)

{
body of the loop
continue label;
}

If we want we can use break statement which causes the control


to jump outside the nearest loop and continue (restart ) the loop

LD3\ContinueLabel.java
1.WAP to demonstrate array structure
Eg: read and display array elements

2.WAP to demonstrate for loop structure


Eg: sorting numbers , array of string

3.WAP to demonstrate switch case


Eg: check whether an alphabet/digit is a vowel or number
Classes and Objects

Class describe objects that share characteristics , methods ,


relationships and semantics

Each class has a name, attribute and operations which provides the
behavior for the object

When we write a oops program , first we define a class they serve as


a blueprint from which objects are created

class classname [ extends superclassname]


{ [field declaration; ]
[method declaration; ]
}
Field and method declaration

Field Declaration

Data is encapsulated in a class by placing data field inside the


body of the class definition, these variables are called
instance/member variables because they are created whenever
an object of the class is instantiated

Class Rectangle

{
int length , width ;

}
Method Declaration

Methods are declared inside the body of the class but


immediately after the declaration of instance variables

type methodname [ parameter list comma separated ]

{
method body;
}

Method declaration will have four basic parts:


The name of the method
The type of the value the method returns
A list of parameters
Body of the method
LD4\DemoBox.java
Constructors

Constructors and methods differ in three aspects of the


signature: modifiers, return type, and name.

Like methods, constructors can have any of the access modifiers:


public, protected, private, or none

Unlike methods, constructors can take only access modifiers.


Therefore, constructors cannot be abstract, final, static,
or synchronized.

Methods can have any valid return type, or no return type, in


which case the return type is given as void. Constructors have no
return type, not even void.
In terms of the signature, methods and constructors have
different names.

Constructors have the same name as their class; by


convention, methods use names other than the class name.

If the Java program follows normal conventions, methods will


start with a lowercase letter, constructors with an uppercase
letter.

Also, constructor names are usually nouns because class


names are usually nouns ,method names usually indicate
actions.

LD4\DemoConBox.java
Copy constructor

The one object is the exact replica of another, if any changes is


made in the first one it will inadvertently change the values of the
instance variables of the second one which is the copy of the first
one.

So you have to be careful and better not to declare copy


constructor as public because during inheritance it doesnt
satisfy Open-Closed Principle (OCP).

The OCP, by Bertrand Meyer, states that software entities should


be open for extension, but closed for modifications.

LD4\ConstructorDemo.java
Method Overloading

In java it is possible to create methods that have the same


name , but different parameter lists and different definitions,
this is called method overloading

Method overloading is used when objects are required to


perform similar tasks but using different input parameters

When we call a method in an object java matches up the


method name first and then the number of parameters to
decide which one of the definition to execute , this process is
known as polymorphism

LD4\OverLoadDemo.java
Static

These are the defined members that is common to all the


objects and accessed without using a particular object

The member belongs to the class as a whole rather than


the objects created from the class

static int count ;


static int max(int x, int y);

The member that are declared static called static members


Since they are associated with the class itself rather than
individual objects, static variable and static methods called
class variables and class methods
Java static variable

Static variables are used when we want to have a variable


common to all instance of a class
LD4\TotalObjects.java

Java creates only one copy of a static variable which can be used
even if class is never actually instantiate
LD4\DemoStatic.java

Static methods have several limitations


1. They can only call other static methods
2. They can only access static data
If you declare any variable as static, it is known static variable.
The static variable can be used to refer the common property of all
objects . The static variable gets memory only once in class area at
the time of class loading.

Advantage of static variable


It makes your program memory efficient (i.e it saves memory).

Java static method


If you apply static keyword with any method, it is known as static
method.
A static method belongs to the class rather than object of a class.
A static method can be invoked without the need for creating an
instance of a class. Static method can access static data member
and can change the value of it.
Java static block

Is used to initialize the static data member.


It is executed before main method at the time of class loading.
LD4\StaticBlock.java

Why main() is static ?

because object is not required to call static method if it were


non-static method, jvm create object first then call main() method
that will lead the problem of extra memory allocation.
Nesting of Methods

Methods can be called by an object of that class

But a method can be called by using only its name by another


method of the same class this method is called nesting of
methods

LD4\Nesting.java
1. Write a class Rectangle with members as length and width and a
constructor that initializes length and width to the given values.
Write a function that returns the area of rectangle.

2. Write a class Test with a function that takes the parameter by value.

3. Write a class Test with a function that takes the parameter as object.

4. Write a recursive function (function calling itself) to find factorial of


a given number
String object is immutable whereas StringBuffer/StringBuilder objects are
mutable.
immutable - mean that the value stored in the String object cannot be
changed.

String
String is immutable ( once created can not be changed )object .
The object created as a String is stored in the Constant String Pool .
Every immutable object in Java is thread safe ,that implies String is
also thread safe . String can not be used by two thread
simultaneously.
String once assigned can not be changed .

String myString = Hello;

Next, you want to append Guest to the same String. What do you do?

myString = myString + Guest;


StringBuffer/StringBuilder objects are mutable, we can make changes to
the value stored in the object.

whats the difference between StringBuffer and StringBuilder?


StringBuffer and StringBuilder have the same methods with one difference
and thats of synchronization. StringBuffer is synchronized each method in
StringBuffer is synchronized that is StringBuffer is thread safe .

Due to this it does not allow two threads to simultaneously access the
same method . Each method can be accessed by one thread at a time .
whereas StringBuilder is not synchronized( which implies it isnt thread
safe).

String s = Hello;
s = s + World;
system.out.println(s);

StringBuilder sb = new StringBuilder(Hello);


sb.append( World);
system.out.println(sb);
Strings and StringBuffer
java.lang.Object
java.lang.String
The String class represents character strings. All string literals in
Java programs, such as "abc", are implemented as instances of
String class.
Strings are constant; their values cannot be changed after they
are created.

String firstname;
Or
String firstname = new String(anil);

To get the length of string


int m= firstname.length();
String Functions
concat(String str)
Concatenates the specified string to the end of this string.

replace (char oldChar, char newChar) Returns a new string resulting from
replacing all occurrences of oldChar in this string with newChar.

Trim() Returns a copy of the string, with leading and trailing whitespace
omitted.

toLowerCase () Converts all of the characters in this String to lower case


using the rules of the default locale.

toUpperCase () Converts all of the characters in this String to upper case


using the rules of the default locale.

charAt (int index) Returns the character at the specified index.


indexOf

valueOf(char c)
Returns the string representation of the char argument.
StringBuffer functions

insert()
This is the insert() function used to insert any string or
character at the specified position in the given string.
reverse()
This is the reverse() function used to reverse the string
present in string buffer.
setCharAt()
This is the setCharAt() function which is used to set the
specified character in buffered string at the specified position
of the string in which you have to set the given character.

charAt()
This is the charAt() function which is used to get the
character at the specified position of the given string.
substring()
This is the substring() function which is used to get the sub
string from the buffered string from the initial position to end
position (these are fixed by you in the program).
substring()
This is the substring() function which is used to get the sub string from the
buffered string from the initial position to end position (these are fixed by
you in the program).

deleteCharAt()
This is the deleteCharAt() function which is used to delete the specific
character from the buffered string by mentioning that's position in the string.
length()
This is the length() function is used to finding the length of the buffered
string.

delete()
This is the delete() function is used to delete multiple character at once
from n position to m position (n and m are will be fixed by you.) in the
buffered string.

capacity()
This is the capacity() function is used to know about the current characters
kept
..\Unit2\LD2\SortStringNum.java
..\Unit2\LD2\StringDemo.java
..\Unit2\LD2\stringBufferDemo.java

Garbage collection (GC) is the process that aims to free up


occupied memory that is no longer referenced by any reachable
Java object, and is an essential part of the Java virtual machine's
(JVM's) dynamic memory management system.

The space occupied by previously referenced objects is freed and


reclaimed to enable new object allocation.

finalize() is called before Garbage collector reclaim the Object, its


last chance for any object to perform cleanup activity i.e. releasing
any system resources held, closing connection if open etc

..\Unit1\LD4\DistructorDemo.java

S-ar putea să vă placă și