Java Programming: OOP Concepts Explained
Java Programming: OOP Concepts Explained
C++ java
1)C++ is platform-dependent. 1)java is platform
Independent.
2)used for system programming. 2)used for application
programming.
3)supports multiple inheritance. 3)doesn't support multiple
[Link] can achieve
by interfaces.
4)supports operator overloading, 4) doesn't support operator
method overloading. Overloading.
5)Uses compiler only. 5)uses compiler and
interpreter.
6)Supports both call by value and 6)supports call by value
reference . only.
7)code is not portable. 7)code is portable.
8)Supports pointers, structures and 8)supports threads and
Unions. interfaces.
9)it requires explicit memory 9)it includes automatic garbage
Management collection.
10)it uses only compiler. 10)it uses both compiler and
interpreter
Class:It is a blueprint or prototype from which objects are [Link] defines a
class that models the state and behaviour of real world object.
Eg :
class Democlass{
[Link]("class Demo");
Output:
class Demo
Principles of oo language:
[Link]
[Link]
[Link]
[Link]
Inheritance(parent-child relationship):
It is a mechanism in which one object acquires all the
properties and behaviours of a parent object. It represents IS-
A relationship. For method overriding and code
EX:
class Employee{
float salary=40000;
int bonus=10000;
OUTPUT:
Ex:
class Animal{
void eat(){
[Link]("eating");
void bark(){
[Link]("barking");
class TestInheritance{
[Link]();
[Link]();
Output:
S:\note java>javac [Link]
barking
eating
EX:
class Animal{
void eat(){
[Link]("eating");
void bark(){
[Link]("barking");
void weep(){
[Link]("weeping");}
class MultipleInheritance{
[Link]();
[Link]();
[Link]();
Output:
weeping
barking
eating
Hierarchial Inheritance:
When two or more classes inherits a single class, it is
known as hierarchical inheritance.
Ex:
class Animal{
void eat(){
[Link]("eating");
}
}
class Dog extends Animal{
void bark(){
[Link]("barking");
}
}
class Cat extends Animal{
void meow(){
[Link]("meowing");
}
}
class TestInheritance{
public static void main(String args[]){
Cat c=new Cat();
[Link]();
[Link]();
}
}
OUTPUT:
S:\note java>javac [Link]
S:\note java>java TestInheritance
meowing
eating
Abstraction:
It is a process of hiding the implementation details and showing only
functionality to the user.
[Link] class.
[Link]
>Abstract class:
It is a type of class in Java that is declared by the abstract keyword.
It can have both abstract methods and concrete [Link] Abstract
[Link] default cases for [Link] default cases for
[Link] to define constructors,static blocks and nonstatic
blocks,static and nonstatic methods,static and nonstatic [Link]
creation not [Link] cannot be instantiated.
Example:
[Link]();
Output
running safely
>Interface:
It can have any no. of abstract [Link] cannot have any concrete
methods. inside interface by default every method is ‘public’ or
‘abstract’.By default every variable are ‘public static final’.not possible to
declare constructors,static and nonstatic blocks,static methods.
>Inside it public methods are allowed but not private and [Link]
interface static,final,synchronized(illegal) methods are not [Link]
creation is not possible. Interfaces can extend other interfaces but not
classes. Interfaces cannot be instantiated .
interface printable{
void print();
}
class A6 implements printable{
public void print(){
[Link]("Hello");
}
public static void main(String args[]){
A6 obj = new A6();
[Link]();
}
}
Output:
class overloading{
void m1() {
[Link]("method display");
}
void m1(int a) {
[Link]("a= "+a);
}
}
class TestOverloading{
public static void main(String[] args){
overloading obj=new overloading();
obj.m1();
obj.m1(30);
}
}
OUTPUT:
S:\note java>javac [Link]
S:\note java>java TestOverloading
method diaplay
a= 30
[Link] polymorphism.
>Method overriding:If subclass (child class) has the same method as
declared in the parent class, it is known as method overriding in Java.
class Vehicle{
void run(){
[Link]("Vehicle is running");
void run(){
[Link]();
OUTPUT:
Types of Constructors:
[Link] constructors.(no-arg)
[Link] constructors.(passing parameters)
Example:
class student{
String name;
int rno;
student(){
name="ABC";
rno=123;
}
student(String str,int num){
name=str;
rno=num;
}
public static void main(String args[]){
student obj=new student();
student obj1=new student("DEF",456);
[Link]([Link]);
[Link]([Link]);
[Link]([Link]);
[Link]([Link]);
}
}
OUTPUT:
S:\note java>javac [Link]
S:\note java>java student
ABC
123
DEF
456 .
Destructors:
It is a special method that automatically gets called when
an object is no longer used. When an object completes its life-
cycle the garbage collector deletes that object and deallocates
or releases the memory occupied by the object.
>garbage collector invokes finalize() method(available in object class)
before destruction of any object. finalize method invoked , to close
the resources connected to object.
Example:
public class DestructorExample
{
protected void finalize(){
[Link]("object destroyed by garbage collector");
}
public static void main(String[] args) {
DestructorExample de = new DestructorExample ();
[Link]();
de = null;
[Link]();
[Link]("removed the resources connection with
object");
}
}
Output:
S:\note java>javac [Link]
S:\note java>java DestructorExample
object destroyed by garbage collector
removed the resources connection with object
object destroyed by garbage collector
operator overloading:
class overload
{
void add(){
int a=10,b=20;
int c=a+b;
[Link]("c:"+c);
}
void add(int x,int y){
int z=x+y;
[Link]("z:"+z);
}
}
class Ooverload{
public static void main(String args[]){
overload obj=new overload();
[Link]();
[Link](40,60);
}
}
OUTPUT:
S:\note java>javac [Link]
S:\note java>java Ooverload
c:30
z:100
Static variables:
It can be access directly(single class).access with help of
classname(multiple class)
In single class:
class staticexample
{
static int a=10;
static void myMethod()
{
[Link]("static method displayed");
}
static{
[Link]("static block");
}
public static void main(String[] args)
{
[Link](a);
myMethod();
}
}
OUTPUT:
S:\note java>javac [Link]
S:\note java>java staticexample
static block
10
static method displayed
In Multiple class:
class staticexample
{
static int a=10;
static void myMethod()
{
[Link]("static method displayed");
}
static{
[Link]("static block");
}
}
class example3{
public static void main(String[] args)
{
[Link](staticexample.a);
[Link]();
}
}
Output:
S:\note java>javac [Link]
S:\note java>java staticexample
static block
10
static method displayed
Non-Static methods :
>A non-static method does not have the keyword static before
the name of the method.
EX:
class nonstaticexample{
[Link]();
}
Output:
Access specifiers:
[Link]: The access level of a private modifier is only within
the class. It cannot be accessed from outside the class.
Ex:
class A{
[Link]("Hello java");
A obj=new A();
[Link]([Link]);
[Link]();
Output:
[Link]();
2 errors
package pack;
class A{
void msg(){
[Link]("Hello");
Filename:[Link]
package mypack;
class B{
[Link]();
package pack;
public class A{
[Link]("Hello");
package mypack;
class B extends A{
[Link]();
}
}
Filename :[Link]
package pack;
public class A{
[Link]("Hello");
Filename:[Link]
package mypack;
class B{
[Link]();
OUTPUT:
Hello
Static Binding (also known as Early Binding):
When type of the object is determined at compiled time(by the
compiler), it is known as static binding.
class Dog{
[Link]("dog is eating...");
[Link]();
OUTPUT:
dog is eating...
class Animal{
void eat(){
[Link]("animal is eating");
void eat(){
[Link]("dog is eating");
[Link]();
OUTPUT:
dog is eating
UNIT-II
Features of java:
1. Simple: easy to learn, syntax is simple(c++), clean and easy to understand
removed unessential [Link] need to remove unessential objects(automatic
garbage collector).
3. Portable: Can carry Java bytecode to any platform. It doesn't require any
implementation.
4. platform independent: Java is a write once, run anywhere language. Java code
can be run on multiple platforms.
5. Secured-no explicit pointer, problems like virus and threats are eliminated
6. Robust-java has inbuilt exception handling and memory, Management features.
7. Architecture neutral-there is no implementation of dependent features, size of
primitive data types are fixed.
8. Interpreted-java programs to generate byte code. byte code can be downloaded
and interpreted by interpreter in java.
9. High Performance-problem with interpreter inside JVM is that it is slow. Java
developers introduce JIT compiler which enhances speed of Execution.
10. Multithreaded: java uses several threads to execute different blocks of [Link]
creating multiple threads is called Multithreading
11. Distributed-java makes us able to access files by calling methods from any
machine on internet.
12. Dynamic- In java all operation(memory allocation and deallocation) are
performed at run time.
Documentation section:
Package declaration:
Package packagename
Import statements:
Interface section(optional):
Void m1();
Void m2();
Class Definition:
We define [Link] program can contain more than one [Link] is blue print of java
[Link] contain information about userdefined methods,variables,and [Link]
java program has atleast one class that contains main() method.
Class classname{
Class classname{
Datatype variablename;
}
1. public class Demo //class definition
2. {
3. public static void main(String args[])
4. {
5. void display()
6. {
7. [Link]("Welcome to javatpoint");
8. }
9. //statements
10. }
11. }
JAVA PROGRAM:
1. /*Program name: Number*/
2. //Author's name: sowmya
3. /*show enter number.*/
4. //imports the Scanner class of the [Link] package
5. import [Link];
6. //class definition
7. public class Number
8. {
9. //main method
10. public static void main(String args[])
11. {
12. //variables to be used in program
13. int x; //It is the number variable
14. Scanner sc= new Scanner([Link]);
15. [Link]("Enter number: ");
16. //reading a number from the user
17. x=[Link]();
18. [Link]("entered number is: " +x);
19. }
20. }
OUTPUT:
Enter number:3
Ex:Byte(1),short(2byte),int(4),long(8),float(4),double(8),Boolean(1),char(2).
2)nonprimitive- These data types are not actually defined by the programming
language but are created by the programmer. They are also called “reference
variables” or “object references” since they reference a memory location which
stores the data. It can be used to call methods to perform certain [Link] can be
null. start with upper case [Link] nonprimitives datatypes have same size.
For Loop:
Syntax of for loop:
for(initialization; condition ; increment/decrement)
{
statement(s);
}
class ForLoopExample {
public static void main(String args[]){
for(int i=10; i>1; i--){
[Link]("The value of i is: "+i);
}
}
}
If-else
Syntax:
if(condition) {
Statement(s);
}
else {
Statement(s);
}
While loop:
Syntax of while loop
while(condition)
{
statement(s);
}
class WhileLoopExample {
public static void main(String args[]){
int i=10;
while(i>1){
[Link](i);
i--;
}
}
}
Output:
10
9
8
7
6
5
4
3
2
do-while loop:
do
{
statement(s);
} while(condition);
class DoWhileLoopExample {
public static void main(String args[]){
int i=10;
do{
[Link](i);
i--;
}while(i>1);
}
}
Output:
10
9
8
7
6
5
4
3
2
Operators: It is a symbol which is used to perform operations.
int a=10,b=11,c=20;
[Link](a*b);
[Link](a==b);
a+=3;
[Link](a);
[Link](a++);
[Link](a<b&a<c);
[Link](a<b&&a<c);
[Link](a>b||a<c);
[Link](a++ + ++a);
[Link](10*10/5+3-1*4/2);
[Link](10<<2);//10*2^2=10*4=40
[Link](10>>2);//10/2^2=10/4=2
Output: Value of b is : 30
Value of b is : 20
Parameter Passing:
>Function parameters:
Syntax: functionname(datatype variablename);
>Actual parameters:
Syntax: functionname(variable name(s));
class Bike9{
final int speedlimit=90;
void run(){
speedlimit=400;
}
public static void main(String args[]){
Bike9 obj=new Bike9();
[Link]();
}
}
OUTPUT:
S:\note java>javac [Link]
[Link][Link] error: cannot assign a value to final variable speedlimit
speedlimit=400;
^
1 error
FinalKeyword with Methods: If you make any method as final,
you cannot override it.
>Final method can be inherited.
class Bike9{
final void run(){
[Link]("running");
}
}
class Honda extends Bike9{
void run(){
[Link]("running safely with 100kmph");
}
public static void main(String args[]){
Honda honda= new Honda();
[Link]();
}
}
OUTPUT:
S:\note java>javac [Link]
[Link][Link] error: run() in Honda cannot override run() in Bike9
void run(){[Link]("running safely with 100kmph");}
^
overridden method is final
1 error
Final Keyword with classes: If you make any class as final, you
cannot extend it.
final class Bike9{
}
class Honda1 extends Bike9{
void run(){
[Link]("running safely with 100kmph");
}
public static void main(String args[]){
Honda1 honda= new Honda1();
[Link]();
}
}
OUTPUT:
S:\note java>javac [Link]
[Link][Link] error: cannot inherit from final Bike9
class Honda1 extends Bike9{
^
1 error
NOTE: A final variable that is not initialized at the time of
declaration is known as blank final variable. It can be initialized
only in constructor.
A static final variable that is not initialized at the time of
declaration is known as static blank final variable. It can be
initialized only in static block.
If you declare any parameter as final, you cannot change the
value of it
Stack clas:
import [Link].*;
public class Stackoperations {
public static void main(String a[]){
Stack stack = new Stack();
[Link]("Initial stack : " + stack);
[Link]("Is stack Empty? : " + [Link]());
[Link](10);
[Link](20);
[Link](30);
[Link](40);
[Link]("Stack after push operation: " + stack);
[Link]("Element popped out:" + [Link]());
[Link]("Stack after Pop Operation : " + stack);
[Link]("Element 10 found at position: " + [Link](10));
[Link]("Is Stack empty? : " + [Link]());
}
}
Output:
S:\note java>javac [Link]
S:\note java>java Stackoperations
Initial stack : []
Is stack Empty? : true
Stack after push operation: [10, 20, 30, 40]
Element popped out:40
Stack after Pop Operation : [10, 20, 30]
Element 10 found at position: 3
Is Stack empty? : false
UNIT-III
Specialization form of inheritance satisfies substitutability or
not :
substitutability: if B is a subclass of A, anywhere we expect an instance of A we
can use an instance of B.
specialization -- the subclass is a special case of the parent [Link] holds
substitutability.
class parentclass{
void parent(){
[Link]("parentclass");
}
}
class subclass extends parentclass {
void sub(){
[Link]("subclass");
}
}
class Testspecialization {
public static void main(String args[]){
subclass obj=new subclass();
[Link]();
[Link]();
}
}
OUTPUT:
interface:
interface printable{
void print();
}
class A6 implements printable{
public void print(){
[Link]("Hello");
}
public static void main(String args[]){
A6 obj = new A6();
[Link]();
}
}
Output:
Concrete Class
A concrete class in Java is a type of subclass, which implements all the abstract methods
of its super abstract class which it extends to. It also has implementations of all methods
of interfaces it implements.
Example:
int c = a + b;
return c;
int c = a - b;
return c;
}
public void display(){
[Link]("Hello");
[Link]([Link](25, 347));
[Link]([Link](500, 456));
[Link]();
Output:
372
44
Hello
OUTPUT:
S:\note java>javac [Link]
S:\note java>java Testconstructor
Maximum Speed: 120
Inheritance(IS-A):it is of two types
class inheritance
interface inheritance
[Link] is unidirectional. If you we have extends keyword or implements
keyword in a class declaration, then this class is said to have IS-A
[Link] is static binding(compile time).tightly [Link] reusuability
.reduce redundancy.
class Animal{
String name="Orio";
String type="Dog";
[Link]("Name:"+[Link]);
[Link]("Type:"+[Link]);
}
Composition(Has-A)
use of instance variables that are references to other [Link] is dynamic
binding(run time).loosely coupled.
Exception: Exceptions:
Exceptions are the errors that occurs during execution of program that
interrupts normal flow of program..
Runtime/unchecked exception:It is not checked at compile-
time, they occurs at runtime.
class unchecked{
public static void main(String args[])
{
int a=10,b=0;
int res=a/b;
[Link](res);
}
}
Output:
S:\note java>javac [Link]
S:\note java>java unchecked
Exception in thread "main" [Link]: / by zero
at [Link]([Link]:
Checked/static:it is checked at compile time.
import [Link].*;
public class checked {
public static void main(String args[]) {
File file = new File("S://notejava");
Output:
S:\note java>javac [Link]
S:\note java>java check
Computer
[Link]: / by zero
Programming
Explanation: The statements that may raise an exception are placed in the ‘try’
block. If an exception is raised the control goes to the ‘catch’ block.
*At a time only one exception occurs and at a time only one
catch block is executed.
Output:
S:\note java>javac [Link]
S:\note java>java Nestedtry
[Link]: / by zero
[Link]: Index 5 out of bounds for length 5
out of try catch block.
Finally try:
*It is always executed whether exception is handled or not.
Output1:
S:\note java>javac [Link]
S:\note java>java IOB
Enter count:
5
Enter values:
90
80
70
60
50
Elements are:
[90, 80, 70, 60, 50]
Enter index:
3
Element is:60
End
Output2:
Enter count:
3
Enter values:
50
90
80
Elements are:
[50, 90, 80]
Enter index:
4
[Link]: Index 4 out of bounds for length 3
end
NullPointer Exception:
public class NullExceptionExample{
public static void main(String args[]){
String s="sowmya",w=null;
try{
[Link]([Link]());
[Link]([Link]());
}
catch(NullPointerException e){
[Link](e);
}
[Link]("length of string");
}
}
OUTPUT:
S:\note java>javac [Link]
S:\note java>java NullExceptionExample
6
[Link]
length of string
NumberFormatException:
Source code:
import [Link].*;
class NFE{
public static void main(String args[]){
try{
int num=[Link]("XYZ");
[Link](num);}
catch(NumberFormatException e){
[Link](e);}
finally{
[Link]("end");}
}
}
Output1:
If input is XYZ.
S:\note java>javac [Link]
S:\note java>java NFE
[Link]: For input string: "XYZ"
end
output2:
if input is 123.
S:\note java>javac [Link]
S:\note java>java NFE
123
End
ClassNotFoundException:
class FileA{}
class FileB{}
class MyClass{
public static void main(String[] args)
{
try{
Class cls =[Link]("FileC");
ClassLoader obj=[Link]();
[Link]("found: " + [Link]());
}
catch(ClassNotFoundException e)
{
[Link]("class not found in class path");
}
}
}
OUTPUT:
S:\note java>javac [Link]
S:\note java>java MyClass
class not found in class path
Method 2:
class FileA{}
class FileB{}
class MyClass{
public static void main(String[] args) throws ClassNotFoundException{
Class cls =[Link]("FileB");
ClassLoader obj=[Link]();
[Link]("found: " + [Link]());
}
}
Output :
Output:
S:\note java>javac [Link]
1)S:\note java>java CLA ab
Divide by zero exception
end
2)S:\note java>java CLA ab df
IndexOutOfBounds exception
end
3)S:\note java>java CLA ab df gh
user defined exception
end
Output:
S:\note java>javac [Link]
1)S:\note java>java strexception
enter two strings:
vinu
vinu
same strings ,no exception
end
[Link](10);
}
catch(invalidException ex){
[Link]("caught Exception");
[Link]([Link]());
}
}
}
Termination or Resumptive Model:
When an exception is thrown, control is transferred to the catch block that
handles the error. programmer has 2 choices. he can print error message and
exit from program. this technique is called Termination Model. The user can
also continue execution by calling some other function after printing the error
message. this technique is called as Resumptive model.
If exception handling is not provided, then in java application the
program terminates automatically after printing the default exception
message.
Source code:
class TERORRESEXAMPLE{
public static void main(String arg[]) {
try
{
[Link](4/0);
}
catch(ArithmeticException e)
{
[Link](e);
[Link](0);
}
[Link]("resumptive model");
}
}
OUTPUT 1: Termination
S:\note java>javac [Link]
S:\note java>java TERORRESEXAMPLE
[Link]: / by zero
OUTPUT2: Resumptive model
S:\note java>javac [Link]
S:\note java>java TERORRESEXAMPLE
[Link]: / by zero
resumptive model
Synchronisation :
It is the capability to control the access of multiple threads to any shared
resource. without synchronisation the output is inconsistent.
Synchronized block:
It is synchronized on same object can only have one thread during executing
inside them at the same time .All other threads attempting to enter the
synchronized block are blocked until the thread inside the synchronized block
exits the block.
Ex: void synchronizedEx(){
Synchronized(this){
//All code goes here..
}
}
Source code:
class sync {
synchronized static void table(int n){
for(int i=1;i<=10;i++){
[Link](n*i);
try {
[Link](400);}
catch(Exception e){
[Link](e)}
}
}
}
class Thread1 extends Thread{
public void run(){
[Link](1);
}
}
class Thread2 extends Thread{
public void run(){
[Link](10);
}
}
public class testsync{
public static void main(String args[]){
Thread1 t1=new Thread1();
Thread2 t2=new Thread2();
[Link]();
[Link]();
}
}
Output:
S:\note java>javac [Link]
S:\note java>java testsync
1
2
3
4
5
6
7
8
9
10
10
20
30
40
50
60
70
80
90
100
Source code:
class Thread1 extends Thread{
synchronized public void run(){
try{
sleep(1000);
[Link]("good mrng");}
catch(Exception e){}
}
}
class Thread2 extends Thread{
synchronized public void run(){
try{
sleep(2000);
[Link]("hello");}
catch(Exception e){}
}
}
public class instsync{
public static void main(String args[]){
Thread1 t1=new Thread1();
Thread2 t2=new Thread2();
[Link]();
[Link]();}
}
output:
S:\note java>javac [Link]
S:\note java>java instsync
good mrng
hello
Threads:
threads allows a program to operate more efficiently by doing multiple
things at the same time.
create a thread:
1. Extending the Thread class
2. Implementing the Runnable Interface
Differences:
Runnable interface extending thread class
Runnable is an interface in Java to create a The thread is a class in Java to create a thread
thread that allows many threads to share the where each thread has a unique object
same thread object. associated with it.
In Runnable, multiple threads share the same In Thread class, each thread creates a unique
object, so require less memory. object, therefore requires more memory.
Source code:
import [Link].*;
class Oddeven{
public static void main(String args[]){
Thread1 obj1=new Thread1();
[Link]();
Thread2 obj2=new Thread2();
[Link]();
}
}
class Thread1 extends Thread {
public void run(){
try{
[Link]("even numbers");
sleep(1000);
for(int i=0;i<=20;i+=2){
[Link](i);}
}
catch(Exception e){
[Link](e);}
}
}
class Thread2 extends Thread {
public void run(){
try{
sleep(2000);
[Link]("odd numbers");
for(int i=1;i<=20;i+=2){
[Link](i);}
}
catch(Exception e){
[Link](e);}
}
}
Output:
S:\note java>javac [Link]
S:\note java>java Oddeven
even numbers
0
2
4
6
8
10
12
14
16
18
20
odd numbers
1
3
5
7
9
11
13
15
17
19
Source code:
class Thread1 implements Runnable{
public void run(){
try{
[Link](1000);
[Link]("Oops Lab");
}
catch(Exception e){
[Link](e);}
}
}
class Thread2 implements Runnable{
public void run(){
try{
[Link](2000);
[Link]("java programming");
}
catch(Exception e){
[Link](e);}
}
}
class Thread3 implements Runnable{
public void run(){
try{
[Link](3000);
[Link]("multithreading");
}
catch(Exception e){
[Link](e);}
}
}
class Runthread{
public static void main(String args[]){
Thread1 obj1=new Thread1();
Thread2 obj2=new Thread2();
Thread3 obj3=new Thread3();
Thread ob1=new Thread(obj1);
[Link]();
Thread ob2=new Thread(obj2);
[Link]();
Thread ob3=new Thread(obj3);
[Link]();
}
}
Output:
S:\note java>javac [Link]
S:\note java>java Runthread
Oops Lab
java programming
multithreading
Threads:
1)Printing 5 numbers from 5 to 1:
source code:
import [Link].*;
class Num5{
public static void main(String args[]){
numbers obj=new numbers();
[Link]();
}
}
class numbers extends Thread {
public void run(){
try{
[Link]("5 numbers");
for(int i=5;i>=1;i--){
sleep(1000);
[Link](i);}
}
catch(Exception e){
[Link](e);}
}
}
Output:
S:\note java>javac [Link]
S:\note java>java Num5
5 numbers
5
4
3
2
1
Week-12
Q. Reverse a list of elements using stack class in
java.
Source code:
import [Link].*;
import [Link].*;
public class Elementstack{
public static void main(String args[]) {
Stack<Integer> stack = new Stack<Integer>();
Scanner S=new Scanner([Link]);
[Link]("Enter count:");
int length=[Link]();
int a[]=new int[length];
[Link]("Enter the elements:");
for(int i=0;i<[Link];i++){
a[i] = [Link]();
[Link](a[i]);}
[Link]("Original List:");
[Link](stack);
for(int i=0;i<[Link];i++){
a[i] = [Link]();}
[Link]("Reverse list: ");
for(int i=0;i<[Link];i++){
[Link](a[i]);}
}
}
Output:
S:\note java>javac [Link]
S:\note java>java Elementstack
Enter count:
5
Enter the elements:
90
80
70
60
50
Original List:
[90, 80, 70, 60, 50]
Reverse list:
50
60
70
80
90
Output:
CLIENT PROGRAM:
import [Link];
import [Link].*;
import [Link];
public class udpClient {
public static void main(String args[]) throws IOException {
Scanner S= new Scanner([Link]);
DatagramSocket ds = new DatagramSocket();
InetAddress ip = [Link]();
byte buf[] = null;
while (true) {
String i= [Link]();
buf = [Link]();
DatagramPacket DpSend = new DatagramPacket(buf, [Link], ip,
3333);
[Link](DpSend);
if ([Link]("bye"))
break; }
}
}
OUTPUT:
OUTPUT:
CLIENTINPUT PROGRAM:
import [Link].*;
import [Link].*;
class CLIENTINPUT{
public static void main(String args[])throws IOException{
Socket S=new Socket([Link](),1065);
BufferedReader BR;
PrintStream PS;
String str;
[Link]("Enter Radius :");
BR=new BufferedReader(new InputStreamReader([Link]));
PS=new PrintStream([Link]());
[Link]([Link]());
BR=new BufferedReader(new
InputStreamReader([Link]()));
str=[Link]();
[Link]("Area of the circle is : "+str);
[Link]();
[Link]();
}
}
Output:
import [Link].*;
import [Link].*;
import [Link].*;
public testswing(){
String language[]={"Java","Python","Android","PHP","Swift"};
add(cb);
[Link](l);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new FlowLayout());
setSize(400, 400);
add(jb1);
add(jb2);
add(jtf);
add(jcb);
add(jrb);
setVisible(true);
new testswing();
OUTPUT:
import [Link].*;
import [Link].*;
static JFrame f;
f = new JFrame("frame");
[Link](new FlowLayout());
c1 = new JComboBox(s1);
[Link](s);
[Link]([Link]);
[Link]([Link]);
[Link](l);
[Link](c1);
[Link](l1);
[Link](p);
[Link](400, 300);
[Link]();
if ([Link]() == c1) {
OUTPUT:
Factorial of a number:
Source code:
import [Link].*;
class Fact{
public static void main(String arg[]){
int fact=1;
int n=[Link](arg[0]);
for(int i=1;i<=n;i++){
fact*=i;}
[Link]("factorial of "+n+" is ="+fact);
}
}
Output:
S:\note java>javac [Link]
S:\note java>java Fact 4
factorial of 4 is =24
Multiplication table:
Source code:
import [Link];
public class Mtable{
public static void main(String args[]){
Scanner S=new Scanner([Link]);
[Link]("enter no:");
int n=[Link]();
[Link]("multiplication table of "+n+"");
for(int i=1;i<=10;i++){
[Link](n+"*"+i+"="+(n*i));
}
}
}
Output:
S:\note java>javac [Link]
S:\note java>java Mtable
enter no:4
multiplication table of 4
4*1=4
4*2=8
4*3=12
4*4=16
4*5=20
4*6=24
4*7=28
4*8=32
4*9=36
4*10=40
Output:
S:\note java>javac [Link]
S:\note java>java maxmin
max:10
min:3
Output:
S:\note java>javac [Link]
S:\note java>java Parray
enter count:4
enter values:3 5 8 9
entered array is:3 5 8 9
Q. Arithmetic operations:
Source code:
import [Link].*;
class AO{
public static void main(String arg[]){
Scanner S=new Scanner([Link]);
[Link]("enter n1 and n2:");
int n1=[Link]();
int n2=[Link]();
[Link]("select operator:");
char operator=[Link]().charAt(0);
switch(operator)
{
case '+':[Link]("add: "+(n1+n2));
break;
case '-':[Link]("sub: "+(n1-n2));
break;
case '*':[Link]("mult: "+(n1*n2));
break;
case '%':if (n1>n2)
[Link]("mod:"+(n1%n2));
else
[Link]("mod:"+(n2%n1));
break;
case '/':if(n1>n2)
[Link]("div:"+(n1/n2));
else
[Link]("div:"+(n2/n1));
break;
default:[Link]("incorect option");
return;
}
}
}
Output:
S:\note java>javac [Link]
S:\note java>java AO
1)enter n1 and n2:4 5
select operator:-
sub: -1
2)S:\note java>java AO
enter n1 and n2:4 6
select operator:*
mult: 24
Output:
S:\note java>javac [Link]
1)S:\note java>java Grade
marks:60 80 85
total:225
per:75 grade:B
2)S:\note java>java Grade
marks:0 40 30
total:70
per:23 FAIL
Q. shortlist of students:
Source code:
import [Link].*;
class shortlist{
public static void main(String arg[]){
Scanner S=new Scanner([Link]);
[Link]("enter students:");
int n=[Link]();
student obj[]=new student[n];
for(int i=0;i<n;i++){
obj[i]=new student();
[Link]("enter details of person:"+(i+1));
obj[i].eligible();}
}
}
class student{
static int mp=80,mt=70;
int per,TM,BL;
void eligible(){
Scanner S=new Scanner([Link]);
[Link]("enter name :");
String name =[Link]();
[Link]("enter percentage :");
per=[Link]();
[Link]("enter backlogs:");
BL=[Link]();
[Link]("enter testmarks :");
TM=[Link]();
if(per>=[Link] && BL==0 && TM>=[Link])
[Link]("ELIGIBLE");
else
[Link]("REGECTED");
}
}
Output:
S:\note java>javac [Link]
S:\note java>java shortlist
enter students:2
enter details of person:1
enter name :
vinu
enter percentage :
90
enter backlogs:
0
enter testmarks :
75
ELIGIBLE
enter details of person:2
enter name :
sowmya
enter percentage :
75
enter backlogs:
1
enter testmarks :
50
REGECTED
Output:
S:\note java>javac [Link]
S:\note java>java Salary
daily wages:200
workdays:28
HRA,ALLOWANCES,INCOMETAX:300 3000 1500
basic salary:5600
final salary:7400
UNIT-V
Collections(single unit of objects) framework
(represent set of classes and interfaces).
It gives the programmer access to prepackaged data structures as well as to
algorithms for manipulating them.
A collection is an object that can hold references to other objects. The collection
interfaces declare the operations that can be performed on each type of collection.
The classes and interfaces of the collections framework are in package [Link].
Interfaces:
Iterable interface: Iterable interface is the root interface for all the collection
classes.
Collection interface:This enables you to work with groups of objects; it is at the top of
the collections hierarchy.
List interface:This extends Collection and an instance of List stores an ordered collection of
elements.
Queue interface: ordered list that is used to hold the elements which are about to be
processed.
Deque interface: we can remove and add the elements from both the side
Set: This extends Collection to handle sets, which must contain unique elements.
Sortedsets: This extends Set to handle sorted sets.
Classes:
Array list:Implements a dynamic array by extending AbstractList.
Linkedlist: Implements a linked list by extending AbstractSequentialList.
Vector: This implements a dynamic array. It is similar to ArrayList, but with some
differences.
Stack: Stack is a subclass of Vector that implements a standard last-in, first-out stack.
Priority Queue: It holds the elements or objects which are to be processed by their
[Link] doesn't allow null values to be stored in the queue.
Array Deque: we can add or delete the elements from both the ends.
import [Link].*;
class Readtest
{
public static void main(String[] args)
{
try
{
File fl = new File("d:/[Link]");
BufferedReader br = new BufferedReader(new FileReader(fl)) ;
String str;
while ((str=[Link]())!=null)
{
[Link](str);
}
[Link]();
[Link]();
}
catch(IOException e) {
[Link]();
}
}
}
import [Link].*;
class WriteTest
{
public static void main(String[] args)
{
try
{
File fl = new File("d:/[Link]");
String str="Write this string to my file";
FileWriter fw = new FileWriter(fl) ;
[Link](str);
[Link]();
[Link]();
}
catch (IOException e)
{ [Link](); }
}
}
Standard streams:
By default, they read input from the keyboard and write output to the display. They also support
I/O operations on files.
Standard Input: This is used to read data from user through input devices.
keyboard is used as standard input stream and represented as [Link].
Standard Output: This is used to project data (results) to the user through output
devices. A computer screen is used for standard output stream and represented
as [Link].
Standard Error: This is used to output the error data produced by the user's
program and usually a computer screen is used for standard error stream and
represented as [Link].
import [Link].*;
[Link](str);
}
Expected output:
Enter text :
this is an Input Stream
You entered String :
this is an Input Stream
flush() Method
To clear the internal buffer, we can use the flush() method. This method forces
the output stream to write all data present in the buffer to the destination file.
Constructors:
BufferedReader(Reader rd)
Methods:
Void close();
Void reset();
int read()l
1. package [Link];
2. import [Link].*;
3. public class BufferedReaderExample {
4. public static void main(String args[])throws Exception{
5. FileReader fr=new FileReader("D:\\[Link]");
6. BufferedReader br=new BufferedReader(fr);
7.
8. int i;
9. while((i=[Link]())!=-1){
10. [Link]((char)i);
11. }
12. [Link]();
13. [Link]();
14. }
15. }
16.
[Link] [Link];
[Link] [Link];
[Link] Main {
20. public static void main(String[] args) {
21. try {
22. FileInputStream file = new FileInputStream("[Link]");
23. BufferedInputStream input = new BufferedInputStream(file);
24. int i = input .read();
25. while (i != -1) {
26. [Link]((char) i);
27. i = [Link]();
28. }
29. [Link]();
30. }
31. catch (Exception e) {
32. [Link]();
33. }
34. }
35.}
String Tokenizer:
[Link] class allows you to break a string into tokens.
import [Link];
public class Simple{
public static void main(String args[]){
StringTokenizer st = new StringTokenizer("my name is khan"," ");
while ([Link]()) {
[Link]([Link]());
}
}
}
Output:my
name
is
khan
String Buffer class:
StringBuffer class is used to create mutable (modifiable) string. The StringBuffer class in
java is same as String class except it is mutable i.e. it can be changed.
StringBuffer(int capacity) creates an empty string buffer with the specified capacity
class StringBufferExample{
[Link]("Java");
[Link](sb);
Output:Hello java
Constructors:
Java InetAddress class:
It represents an IP address. The [Link] class provides methods to get the
IP of any host name.
Method names:
getHostName();
getHostAddress();
1. import [Link].*;
2. class TreeMap1{
3. public static void main(String args[]){
4. TreeMap<Integer,String> map=new TreeMap<Integer,String>();
5. [Link](100,"Amit");
6. [Link](102,"Ravi");
7. [Link](101,"Vijay");
8. [Link](103,"Rahul");
9.
10. for([Link] m:[Link]()){
11. [Link]([Link]()+" "+[Link]());
12. }
13. }
14. }
Output:100 Amit
101 Vijay
102 Ravi
103 Rahul
1. import [Link].*;
2. public class ReaderExample {
3. public static void main(String[] args) {
4. try {
5. Reader reader = new FileReader("[Link]");
6. int data = [Link]();
7. while (data != -1) {
8. [Link]((char) data);
9. data = [Link]();
10. }
11. [Link]();
12. } catch (Exception ex) {
13. [Link]([Link]());
14. }
15. }
16. }
1. import [Link].*;
2. public class WriterExample {
3. public static void main(String[] args) {
4. try {
5. Writer w = new FileWriter("[Link]");
6. String content = "I love my country";
7. [Link](content);
8. [Link]();
9. [Link]("Done");
10. } catch (IOException e) {
11. [Link]();
12. }
13. }
14. }
Output:done
1. import [Link].*;
2. import [Link].*;
3. public class SortListExample1
4. {
5. public static void main(String[] args)
6. {
7. //returns a list view
8. List<String> slist = [Link]("Tanu", "Kamal", "Suman", "Lucky", "Bunty", "A
mit");
9. List<String> sortedList = [Link]().sorted().collect([Link]());
10. [Link]([Link]::println);
11. }
12. }
Output:-
#Sun Aug 24 [Link] IST 2014
password=Codingeek
database=localhost
username=Codingeek
1. import [Link].*;
2. class Persist{
3. public static void main(String args[]){
4. try{
5. //Creating the object
6. Student s1 =new Student(211,"ravi");
7. //Creating stream and writing the object
8. FileOutputStream fout=new FileOutputStream("[Link]");
9. ObjectOutputStream out=new ObjectOutputStream(fout);
10. [Link](s1);
11. [Link]();
12. //closing the stream
13. [Link]();
14. [Link]("success");
15. }catch(Exception e){[Link](e);}
16. }
17. }