Oops Unit4
Oops Unit4
Java features – Java Platform – Java Fundamentals – Data Types - Variables and Arrays -
Expressions, Operators and Control Structures--Classes and Objects – Methods - Constructors –
Destructors.
10
Features of Java
There is given many features of java. The Java Features given below are simple and easy to
understand.
1. Simple
2. Object-Oriented
3. Portable
4. Platform independent
5. Secured
6. Robust
7. Architecture neutral
8. Dynamic
9. Interpreted
10. High Performance
11. Multithreaded
12. Distributed
Simple
Java language is simple because:
SNo need to remove unreferenced objects because there is Automatic
Garbage Collection in java.
syntax is based on C++
Removed many confusing and rarely-used features such as pointers, operator
overloading
Object-oriented
Object-oriented means that organize our software as a combination of different types
of objects that incorporates both data and behaviour.
Basic concepts of OOPs are:
o Object
o Class
o Inheritance
o Polymorphism
o Abstraction
o Encapsulation
Platform Independent
Secured
10
o Classloader: adds security by separating the package for the classes of the local file
system from those that are imported from network sources.
o Bytecode Verifier: checks the code fragments for illegal code that can violate access
right to objects.
o Security Manager: determines what resources a class can access such as reading and
writing to the local disk.
Robust
Robust simply means strong.
Java uses strong memory management. There are lack of pointers that avoids security
problem.
There is automatic garbage collection in java. There is exception handling and type
checking mechanism in java.
Architecture-neutral
There is no implementation dependent features e.g. size of primitive types is fixed.
In C programming, int data type occupies 2 bytes of memory for 32-bit architecture
and 4 bytes of memory for 64-bit architecture. But in java, it occupies 4 bytes of
memory for both 32 and 64 bit architectures.
Portable
We may carry the java bytecode to any platform.
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++)
Distributed
We can create distributed applications in java. RMI and EJB are used for creating
distributed applications. We may access files by calling the methods from any machine on the
internet.
10
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.
10
Features of Object Oriented Programming (OOP)
FEATURES OF OOP:
1. Object
2. Class
3. Data Hiding and Encapsulation
4. Dynamic Binding
5. Message Passing
6. Inheritance
7. Polymorphism
OBJECT: Object is a collection of number of entities. Objects take up space in the memory.
Objects are instances of classes. When a program is executed , the objects interact by sending
messages to one another. Each object contain data and code to manipulate the data. Objects can
interact without having know details of each others data or code.
CLASS: Class is a collection of objects of similar type. Objects are variables of the type class.
Once a class has been defined, we can create any number of objects belonging to that class. Eg:
grapes bannans and orange are the member of class fruit.
Example:
Fruit orange;
10
In the above statement object mango is created which belong to the class fruit.
NOTE: Classes are user define data types.
MESSAGE PASSING: The process by which one object can interact with other object is called
message passing.
POLYMORPHISM: A greek term means ability to take more than one form. An operation may
exhibite different behaviours in different instances. The behaviour depends upon the types of
data used in the operation.
Example:
Method Overloading
Method Overriding
10
Data Types in Java:-
Data types refer to the different sizes and values that can be stored in the variable.Two types of
data type are in Java programming:
(A) Primitive data types: The primitive data types consist of int, float,
boolean, byte, short, long, char and double.
(B) Non-primitive data types: The non-primitive data types include
arrays, interfaces and class etc.
Java Primitive Data Types:-
(1) Byte Data Type: - It is the first data type with least memory size
allocation which can be used for numbers of small ranges.
10
per programming) and on the negative side it can represent the number -1 to128.
(d) The default value for byte is zero (0).
(2) Boolean Data Type: - The boolean data type is a one bit information.
Only two possible values are of Boolean data type. Which are true and
false.
10
of short is 32,767.
(a) Its default value is 0.
(b) It can represent total 65536(216) numbers.
Example:- short s = 10000;
10
(8) Long Data Type:-
It has a 64-bit two's complement integer.
Minimum value long data type is - 9,223,372,036,854,775,808 andmaximum
value of long data type is 9,223,372,036,854,775,807.
(a) Its default value is 0.
(2) Class: - A class is a “user defined data type” from which objects are
created of class. In general, class declarations can include components. And
it consists of data and methods in the form of a unit.
10
{
Public:
char color; double
model;
Public void gear (); // behavior of a car
}
Example: -
interface item
{
Static final int code=101; Static final
string name =”fan”;Void display ();
}
Classes and Objects
Class
o fields
o methods
o constructors
o blocks
o nested class and interface
class <class_name>{
field;
10
method;
}
Object
Object is an instance of a class. Class is a template or blueprint from which objects are
created. So object is the instance(result) of a class.
Object Definitions:
10
Method
new keyword
class Rectangle{
int length;
int width;
void insert(int l, int w){
length=l;
width=w;
}
void calculateArea(){System.out.println(length*width);}
}
class TestRectangle1{
public static void main(String args[]){
Rectangle r1=new Rectangle();
Rectangle r2=new Rectangle();
r1.insert(11,5);
r2.insert(3,15);
r1.calculateArea();
r2.calculateArea();
}
}
Output:
55
45
10
Constructors
class Student
{
int marks;
String name;
public Student(int m,String s)
{
marks=m;
name=s;
}
public void display()
{
System.out.println("Name: "+name+ "\nMark: "+marks);
}
}
class EX
{
public static void main(String args[])
{
Student st= new Student(100,"sachin");
st.display();
}
}
Output:
F:\ java>java EX
Name: sachin
Mark: 100
10
Rules for creating java constructor
2. Parameterized constructor
<class_name>(){}
Example of default constructor
class Bike1{
Bike1(){System.out.println("Bike is created");}
10
Bike1 b=new Bike1();
Output:
Bike is created
Output:
111 Karan
222 Aryan
10
Static Fields and Methods
Static Fields
A field as static, then there is only one such field per class. In contrast, each object has its
own copy of all instance fields.
When a number of objects are created from the same class, each instance has its own
copy of class variables. But this is not the case when it is declared as static static.
Eg:
import java.io.*;
class Demo
{
static int i=20;
public void display()
{
System.out.println (i);
}
}
class EX
{
public static void main(String args[])
{
Demo obj1,obj2;
obj1=new Demo();
obj2=new Demo();
++obj1.i;
System.out.print ("x in obj1 :");
obj1.display ();
System.out.print ("x in obj2 :");
obj2.display ();
}
}
OUTPUT:
F:\java>java EX
x in obj1 :21
x in obj2 :21
10
Static Methods
Program:
import java.io.*;
class Student
{
static int marks;
static String name;
class EX
{
public static void main(String args[])
{
Student st=new Student();
st.result(100,"sachin");
Student.display();
}
}
Output:
F:\ java>java EX
Name: sachin
Mark: 100
10
Package
Java package is used to categorize the classes and interfaces so that they can be easily
maintained.
Java package provides access protection.
Java package removes naming collision.
//save as Simple.java
package mypack;
public class Simple{
public static void main(String args[]){
System.out.println("Welcome to package");
}
}
Syntax
Output:Welcome to package
10
Access package from another package
There are three ways to access the package from outside the package.
1. import package.*;
2. import package.classname;
Using packagename.*
If you use package.* then all the classes and interfaces of this package will be
accessible but not sub packages.
The import keyword is used to make the classes and interface of another package
accessible to the current package.
Example
//save by A.java
package pack;
public class A{
public void msg(){System.out.println("Hello");}
}
//save by B.java
package mypack;
import pack.*;
class B{
public static void main(String args[]){
A obj = new A();
obj.msg();
}
}
Output:Hello
10
Subpackage in java
Package inside the package is called the subpackage.
It should be created to categorize the package further.
Example of Subpackage
package com.javatpoint.core;
class Simple{
public static void main(String args[]){
System.out.println("Hello subpackage");
}
}
Output:Hello subpackage
Send the class file to another directory or drive
There is a scenario, I want to put the class file of A.java source file in classes folder of c:
drive. For example:
10
//save as Simple.java
package mypack;
public class Simple{
public static void main(String args[]){
System.out.println("Welcome to package");
}
}
To Compile:
To Run:
To run this program from e:\source directory, you need to set classpath of the directory
where the class file resides.
Output:Welcome to package
10
INTERFACE
An interfaces are declared using interface keyword. The variable inside interface are by
default static and final.
Eg 1:-
import java.io.*;
interface Exam1
{
public static final int m1=100;
public void average();
}
interface Exam2
{
public static final int m2=98;
public void average();
}
10
class Main
{
public static void main(String args[])
{
Student s=new Student();
s.average();
}
}
OUTPUT:
AVERAGE….:99
Eg 2:-
interface Sastha
{
public void display1();
public void display2();
}
OUTPUT:
WELCOME TO SSIET
WELCOME TO SSCE
10
ABSTRACT CLASS
Example:-
import java.io.*;
abstract class Abstract
{ public abstract void callme();
public void display()
{
System.out.println("BASE CLASS");
}
}
class A extends Abstract
{
public void callme()
{
System.out.println("CLASS A");
}
}
class B extends Abstract
{
public void callme()
{
System.out.println("CLASS B");
}
}
10
class Absdemo
{
public static void main(String args[])
{
Abstract obj1=new A();
Abstract obj2=new B();
obj1.callme();
obj2.callme();
}
}
OUTPUT:-
CLASS A
CLASS B
10
Internationalization
MessageBundle_en_US.properties
greeting=Hello, how are you?
MessageBundle_in_ID.properties
greeting=Halo, apa kabar?
10
InternationalizationDemo.java
import java.util.Locale;
import java.util.ResourceBundle;
public class InternationalizationDemo {
public static void main(String[] args) {
}
}
10
Control Structures
Selection Statement
if (condition) statement1;
else statement2;
Nested ifs
A nested if is an if statement that is the target of another if or else.
In nested ifs an else statement always refers to the nearest if statement that is within the
same block as the else and that is not already associated with an else.
if (i == 10) {
if (j < 20) a = b;
if (k > 100) c = d; // this if is
else a = c; // associated with this else
}
else a = d; // this else refers to if(i == 10)
10
switch
The switch statement is Java’s multi-way branch statement.
provides an easy way to dispatch execution to different parts of your code based
on the value of an expression.
provides a better alternative than a large series of if-else-if statements.
switch (expression) {
case value1:
// statement sequence
break;
case value2:
// statement sequence
break;
...
case valueN:
// statement sequence
break;
default:
// default statement sequence
}
class SampleSwitch {
public static void main(String args[]) {
for(int i=0; i<6; i++)
switch(i) {
case 0:
System.out.println("i is zero.");
break;
10
case 1:
System.out.println("i is one.");
break;
case 2:
System.out.println("i is two.");
break;
default:
System.out.println("i is greater than 2.");
}
}
}
switch(count) {
case 1:
switch(target) { // nested switch
case 0:
System.out.println("target is zero");
break;
case 1: // no conflicts with outer switch
System.out.println("target is one");
break;
}
break;
case 2: // ...
IteratIon Statement
(Loops)
10
Iteration Statements
In Java, iteration statements (loops) are:
for
while, and
do-while
A loop repeatedly executes the same set of instructions until a termination condition
is met.
While Loop
While loop repeats a statement or block while its controlling expression is true.
The condition can be any Boolean expression.
The body of the loop will be executed as long as the conditional expression is true.
When condition becomes false, control passes to the next line of code immediately
following the loop.
while(condition)
{
// body of loop
}
Eg:
class While
{
public static void main(String args[]) {
int n = 10;
char a = 'G';
while(n > 0)
{
System.out.print(a);
n--;
a++;
}
}
}
The body of the loop will not execute even once if the condition is false.
The body of the while (or any other of Java’s loops) can be empty. This is because a null
statement (one that consists only of a semicolon) is syntactically valid in Java.
do-while
The do-while loop always executes its body at least once, because its conditional
expression is at the bottom of the
loop. do {
// body of loop
} while (condition);
10
Each iteration of the do-while loop first executes the body of the loop and then evaluates
the conditional expression.
If this expression is true, the loop will repeat. Otherwise, the loop terminates.
for Loop
class ForTable
{
public static void main(String args[])
{
int n;
int x=5;
for(n=1; n<=10; n++)
{
int p = x*n;
System.out.println(x+"*"+n +"="+ p);
}
}
}
10
for (type itr-var : collection) statement-block
type specifies the type.
itr-var specifies the name of an iteration variable that will receive the elements from a
collection, one at a time, from beginning to end.
The collection being cycled through is specified by collection.
With each iteration of the loop, the next element in the collection is retrieved and stored
in itr-var.
The loop repeats until all elements in the collection have been obtained.
class ForEach
{
public static void main(String arr[])
{
int num[] = { 1, 2, 3, 4, 5 };
int sum = 0;
for(int i : num)
{
System.out.println("Value is: " + i);
sum += i;
}
System.out.println("Sum is: " + sum);
}
}
return
The return statement is used to explicitly return from a method.
It causes program control to transfer back to the caller of the method.
Example:
class Return {
public static void main(String args[]) {
boolean t = true;
System.out.println("Before the return.");
if(t) return; // return to caller
System.out.println("This won't execute.");
}
}
10