Oops Java
Oops Java
Oops Java
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
Inheritance.It 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 created.it defines a
class that models the state and behaviour of real world object.
Eg :
class Democlass{
System.out.println("class Demo");
Output:
class Demo
Principles of oo language:
1.inheritance
2.abstraction
3.encapsulation
4.polymorphism
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(){
System.out.println("eating");
void bark(){
System.out.println("barking");
class TestInheritance{
d.bark();
d.eat();
Output:
S:\note java>javac TestInheritance.java
barking
eating
EX:
class Animal{
void eat(){
System.out.println("eating");
void bark(){
System.out.println("barking");
void weep(){
System.out.println("weeping");}
class MultipleInheritance{
d.weep();
d.bark();
d.eat();
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(){
System.out.println("eating");
}
}
class Dog extends Animal{
void bark(){
System.out.println("barking");
}
}
class Cat extends Animal{
void meow(){
System.out.println("meowing");
}
}
class TestInheritance{
public static void main(String args[]){
Cat c=new Cat();
c.meow();
c.eat();
}
}
OUTPUT:
S:\note java>javac TestInheritance.java
S:\note java>java TestInheritance
meowing
eating
Abstraction:
It is a process of hiding the implementation details and showing only
functionality to the user.
1.Abstract class.
2.interface
>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 methods.inside Abstract
class.no default cases for methods.no default cases for
variables.possible to define constructors,static blocks and nonstatic
blocks,static and nonstatic methods,static and nonstatic variables.object
creation not possible.it cannot be instantiated.
Example:
obj.run();
Output
running safely
>Interface:
It can have any no. of abstract methods.it 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 protected.inside
interface static,final,synchronized(illegal) methods are not possible.object
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(){
System.out.println("Hello");
}
public static void main(String args[]){
A6 obj = new A6();
obj.print();
}
}
Output:
class overloading{
void m1() {
System.out.println("method display");
}
void m1(int a) {
System.out.println("a= "+a);
}
}
class TestOverloading{
public static void main(String[] args){
overloading obj=new overloading();
obj.m1();
obj.m1(30);
}
}
OUTPUT:
S:\note java>javac TestOverloading.java
S:\note java>java TestOverloading
method diaplay
a= 30
2.runtime 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(){
System.out.println("Vehicle is running");
void run(){
obj.run();
OUTPUT:
Types of Constructors:
1.Default constructors.(no-arg)
2.parameterized 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);
System.out.println(obj.name);
System.out.println(obj.rno);
System.out.println(obj1.name);
System.out.println(obj1.rno);
}
}
OUTPUT:
S:\note java>javac student.java
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(){
System.out.println("object destroyed by garbage collector");
}
public static void main(String[] args) {
DestructorExample de = new DestructorExample ();
de.finalize();
de = null;
System.gc();
System.out.println("removed the resources connection with
object");
}
}
Output:
S:\note java>javac DestructorExample.java
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;
System.out.println("c:"+c);
}
void add(int x,int y){
int z=x+y;
System.out.println("z:"+z);
}
}
class Ooverload{
public static void main(String args[]){
overload obj=new overload();
obj.add();
obj.add(40,60);
}
}
OUTPUT:
S:\note java>javac Ooverload.java
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()
{
System.out.println("static method displayed");
}
static{
System.out.println("static block");
}
public static void main(String[] args)
{
System.out.println(a);
myMethod();
}
}
OUTPUT:
S:\note java>javac staticexample.java
S:\note java>java staticexample
static block
10
static method displayed
In Multiple class:
class staticexample
{
static int a=10;
static void myMethod()
{
System.out.println("static method displayed");
}
static{
System.out.println("static block");
}
}
class example3{
public static void main(String[] args)
{
System.out.println(staticexample.a);
staticexample.myMethod();
}
}
Output:
S:\note java>javac staticexample.java
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{
obj.method();
}
Output:
Access specifiers:
1.Private: The access level of a private modifier is only within
the class. It cannot be accessed from outside the class.
Ex:
class A{
System.out.println("Hello java");
A obj=new A();
System.out.println(obj.data);
obj.msg();
Output:
obj.msg();
2 errors
package pack;
class A{
void msg(){
System.out.println("Hello");
Filename:B.java
package mypack;
class B{
obj.msg();
package pack;
public class A{
System.out.println("Hello");
package mypack;
class B extends A{
obj.msg();
}
}
Filename :A.java
package pack;
public class A{
System.out.println("Hello");
Filename:B.java
package mypack;
class B{
obj.msg();
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{
System.out.println("dog is eating...");
d1.eat();
OUTPUT:
dog is eating...
class Animal{
void eat(){
System.out.println("animal is eating");
void eat(){
System.out.println("dog is eating");
a.eat();
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 features.no 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 code.so
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 class.java program can contain more than one class.it is blue print of java
program.it contain information about userdefined methods,variables,and constants.every
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. System.out.println("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 java.util package
5. import java.util.Scanner;
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(System.in);
15. System.out.print("Enter number: ");
16. //reading a number from the user
17. x=sc.nextInt();
18. System.out.println("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 operations.it can be
null. start with upper case letter.All 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--){
System.out.println("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){
System.out.println(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{
System.out.println(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;
System.out.println(a*b);
System.out.println(a==b);
a+=3;
System.out.println(a);
System.out.println(a++);
System.out.println(a<b&a<c);
System.out.println(a<b&&a<c);
System.out.println(a>b||a<c);
System.out.println(a++ + ++a);
System.out.println(10*10/5+3-1*4/2);
System.out.println(10<<2);//10*2^2=10*4=40
System.out.println(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();
obj.run();
}
}
OUTPUT:
S:\note java>javac Bike9.java
Bike9.java:4: 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(){
System.out.println("running");
}
}
class Honda extends Bike9{
void run(){
System.out.println("running safely with 100kmph");
}
public static void main(String args[]){
Honda honda= new Honda();
honda.run();
}
}
OUTPUT:
S:\note java>javac Bike9.java
Bike9.java:6: error: run() in Honda cannot override run() in Bike9
void run(){System.out.println("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(){
System.out.println("running safely with 100kmph");
}
public static void main(String args[]){
Honda1 honda= new Honda1();
honda.run();
}
}
OUTPUT:
S:\note java>javac Bike9.java
Bike9.java:3: 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 java.util.*;
public class Stackoperations {
public static void main(String a[]){
Stack stack = new Stack();
System.out.println("Initial stack : " + stack);
System.out.println("Is stack Empty? : " + stack.isEmpty());
stack.push(10);
stack.push(20);
stack.push(30);
stack.push(40);
System.out.println("Stack after push operation: " + stack);
System.out.println("Element popped out:" + stack.pop());
System.out.println("Stack after Pop Operation : " + stack);
System.out.println("Element 10 found at position: " + stack.search(10));
System.out.println("Is Stack empty? : " + stack.isEmpty());
}
}
Output:
S:\note java>javac Stackoperations.java
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 class.it holds
substitutability.
class parentclass{
void parent(){
System.out.println("parentclass");
}
}
class subclass extends parentclass {
void sub(){
System.out.println("subclass");
}
}
class Testspecialization {
public static void main(String args[]){
subclass obj=new subclass();
obj.parent();
obj.sub();
}
}
OUTPUT:
interface:
interface printable{
void print();
}
class A6 implements printable{
public void print(){
System.out.println("Hello");
}
public static void main(String args[]){
A6 obj = new A6();
obj.print();
}
}
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(){
System.out.println("Hello");
System.out.println(obj.add(25, 347));
System.out.println(obj.subtract(500, 456));
obj.display();
Output:
372
44
Hello
OUTPUT:
S:\note java>javac Testconstructor.java
S:\note java>java Testconstructor
Maximum Speed: 120
Inheritance(IS-A):it is of two types
class inheritance
interface inheritance
1.inheritance is unidirectional. If you we have extends keyword or implements
keyword in a class declaration, then this class is said to have IS-A
relationship.it is static binding(compile time).tightly coupled.code reusuability
.reduce redundancy.
class Animal{
String name="Orio";
String type="Dog";
System.out.println("Name:"+p.name);
System.out.println("Type:"+p.type);
}
Composition(Has-A)
use of instance variables that are references to other objects.it 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;
System.out.println(res);
}
}
Output:
S:\note java>javac unchecked.java
S:\note java>java unchecked
Exception in thread "main" java.lang.ArithmeticException: / by zero
at unchecked.main(unchecked.java:
Checked/static:it is checked at compile time.
import java.io.*;
public class checked {
public static void main(String args[]) {
File file = new File("S://notejava");
Output:
S:\note java>javac check.java
S:\note java>java check
Computer
java.lang.ArithmeticException: / 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 Nestedtry.java
S:\note java>java Nestedtry
java.lang.ArithmeticException: / by zero
java.lang.ArrayIndexOutOfBoundsException: 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 IOB.java
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
java.lang.ArrayIndexOutOfBoundsException: 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{
System.out.println(s.length());
System.out.println(w.length());
}
catch(NullPointerException e){
System.out.println(e);
}
System.out.println("length of string");
}
}
OUTPUT:
S:\note java>javac NullExceptionExample.java
S:\note java>java NullExceptionExample
6
java.lang.NullPointerException
length of string
NumberFormatException:
Source code:
import java.util.*;
class NFE{
public static void main(String args[]){
try{
int num=Integer.parseInt("XYZ");
System.out.println(num);}
catch(NumberFormatException e){
System.out.println(e);}
finally{
System.out.println("end");}
}
}
Output1:
If input is XYZ.
S:\note java>javac NFE.java
S:\note java>java NFE
java.lang.NumberFormatException: For input string: "XYZ"
end
output2:
if input is 123.
S:\note java>javac NFE.java
S:\note java>java NFE
123
End
ClassNotFoundException:
class FileA{}
class FileB{}
class MyClass{
public static void main(String[] args)
{
try{
Class cls =Class.forName("FileC");
ClassLoader obj=cls.getClassLoader();
System.out.println("found: " + cls.getName());
}
catch(ClassNotFoundException e)
{
System.out.println("class not found in class path");
}
}
}
OUTPUT:
S:\note java>javac MyClass.java
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 =Class.forName("FileB");
ClassLoader obj=cls.getClassLoader();
System.out.println("found: " + cls.getName());
}
}
Output :
Output:
S:\note java>javac CLA.java
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 strexception.java
1)S:\note java>java strexception
enter two strings:
vinu
vinu
same strings ,no exception
end
obj.check(10);
}
catch(invalidException ex){
System.out.println("caught Exception");
System.out.println(ex.getMessage());
}
}
}
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
{
System.out.println(4/0);
}
catch(ArithmeticException e)
{
System.out.println(e);
System.exit(0);
}
System.out.println("resumptive model");
}
}
OUTPUT 1: Termination
S:\note java>javac TERORRESEXAMPLE.java
S:\note java>java TERORRESEXAMPLE
java.lang.ArithmeticException: / by zero
OUTPUT2: Resumptive model
S:\note java>javac TERORRESEXAMPLE.java
S:\note java>java TERORRESEXAMPLE
java.lang.ArithmeticException: / 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++){
System.out.println(n*i);
try {
Thread.sleep(400);}
catch(Exception e){
System.out.println(e)}
}
}
}
class Thread1 extends Thread{
public void run(){
sync.table(1);
}
}
class Thread2 extends Thread{
public void run(){
sync.table(10);
}
}
public class testsync{
public static void main(String args[]){
Thread1 t1=new Thread1();
Thread2 t2=new Thread2();
t1.start();
t2.start();
}
}
Output:
S:\note java>javac testsync.java
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);
System.out.println("good mrng");}
catch(Exception e){}
}
}
class Thread2 extends Thread{
synchronized public void run(){
try{
sleep(2000);
System.out.println("hello");}
catch(Exception e){}
}
}
public class instsync{
public static void main(String args[]){
Thread1 t1=new Thread1();
Thread2 t2=new Thread2();
t1.start();
t2.start();}
}
output:
S:\note java>javac instsync.java
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 java.util.*;
class Oddeven{
public static void main(String args[]){
Thread1 obj1=new Thread1();
obj1.start();
Thread2 obj2=new Thread2();
obj2.start();
}
}
class Thread1 extends Thread {
public void run(){
try{
System.out.println("even numbers");
sleep(1000);
for(int i=0;i<=20;i+=2){
System.out.println(i);}
}
catch(Exception e){
System.out.println(e);}
}
}
class Thread2 extends Thread {
public void run(){
try{
sleep(2000);
System.out.println("odd numbers");
for(int i=1;i<=20;i+=2){
System.out.println(i);}
}
catch(Exception e){
System.out.println(e);}
}
}
Output:
S:\note java>javac Oddeven.java
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{
Thread.sleep(1000);
System.out.println("Oops Lab");
}
catch(Exception e){
System.out.println(e);}
}
}
class Thread2 implements Runnable{
public void run(){
try{
Thread.sleep(2000);
System.out.println("java programming");
}
catch(Exception e){
System.out.println(e);}
}
}
class Thread3 implements Runnable{
public void run(){
try{
Thread.sleep(3000);
System.out.println("multithreading");
}
catch(Exception e){
System.out.println(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);
ob1.start();
Thread ob2=new Thread(obj2);
ob2.start();
Thread ob3=new Thread(obj3);
ob3.start();
}
}
Output:
S:\note java>javac Runthread.java
S:\note java>java Runthread
Oops Lab
java programming
multithreading
Threads:
1)Printing 5 numbers from 5 to 1:
source code:
import java.util.*;
class Num5{
public static void main(String args[]){
numbers obj=new numbers();
obj.start();
}
}
class numbers extends Thread {
public void run(){
try{
System.out.println("5 numbers");
for(int i=5;i>=1;i--){
sleep(1000);
System.out.println(i);}
}
catch(Exception e){
System.out.println(e);}
}
}
Output:
S:\note java>javac Num5.java
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 java.util.*;
import java.io.*;
public class Elementstack{
public static void main(String args[]) {
Stack<Integer> stack = new Stack<Integer>();
Scanner S=new Scanner(System.in);
System.out.println("Enter count:");
int length=S.nextInt();
int a[]=new int[length];
System.out.println("Enter the elements:");
for(int i=0;i<a.length;i++){
a[i] = S.nextInt();
stack.push(a[i]);}
System.out.println("Original List:");
System.out.println(stack);
for(int i=0;i<a.length;i++){
a[i] = stack.pop();}
System.out.println("Reverse list: ");
for(int i=0;i<a.length;i++){
System.out.println(a[i]);}
}
}
Output:
S:\note java>javac Elementstack.java
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 java.io.IOException;
import java.net.*;
import java.util.Scanner;
public class udpClient {
public static void main(String args[]) throws IOException {
Scanner S= new Scanner(System.in);
DatagramSocket ds = new DatagramSocket();
InetAddress ip = InetAddress.getLocalHost();
byte buf[] = null;
while (true) {
String i= S.nextLine();
buf = i.getBytes();
DatagramPacket DpSend = new DatagramPacket(buf, buf.length, ip,
3333);
ds.send(DpSend);
if (i.equals("bye"))
break; }
}
}
OUTPUT:
OUTPUT:
CLIENTINPUT PROGRAM:
import java.io.*;
import java.net.*;
class CLIENTINPUT{
public static void main(String args[])throws IOException{
Socket S=new Socket(InetAddress.getLocalHost(),1065);
BufferedReader BR;
PrintStream PS;
String str;
System.out.print("Enter Radius :");
BR=new BufferedReader(new InputStreamReader(System.in));
PS=new PrintStream(S.getOutputStream());
PS.println(BR.readLine());
BR=new BufferedReader(new
InputStreamReader(S.getInputStream()));
str=BR.readLine();
System.out.println("Area of the circle is : "+str);
BR.close();
PS.close();
}
}
Output:
import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
public testswing(){
String language[]={"Java","Python","Android","PHP","Swift"};
add(cb);
p.add(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 java.awt.*;
import javax.swing.*;
static JFrame f;
f = new JFrame("frame");
f.setLayout(new FlowLayout());
c1 = new JComboBox(s1);
c1.addItemListener(s);
l.setForeground(Color.red);
l1.setForeground(Color.blue);
p.add(l);
p.add(c1);
p.add(l1);
f.add(p);
f.setSize(400, 300);
f.show();
if (e.getSource() == c1) {
OUTPUT:
Factorial of a number:
Source code:
import java.lang.*;
class Fact{
public static void main(String arg[]){
int fact=1;
int n=Integer.parseInt(arg[0]);
for(int i=1;i<=n;i++){
fact*=i;}
System.out.println("factorial of "+n+" is ="+fact);
}
}
Output:
S:\note java>javac Fact.java
S:\note java>java Fact 4
factorial of 4 is =24
Multiplication table:
Source code:
import java.util.Scanner;
public class Mtable{
public static void main(String args[]){
Scanner S=new Scanner(System.in);
System.out.print("enter no:");
int n=S.nextInt();
System.out.println("multiplication table of "+n+"");
for(int i=1;i<=10;i++){
System.out.println(n+"*"+i+"="+(n*i));
}
}
}
Output:
S:\note java>javac Mtable.java
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 maxmin.java
S:\note java>java maxmin
max:10
min:3
Output:
S:\note java>javac Parray.java
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 java.util.*;
class AO{
public static void main(String arg[]){
Scanner S=new Scanner(System.in);
System.out.print("enter n1 and n2:");
int n1=S.nextInt();
int n2=S.nextInt();
System.out.print("select operator:");
char operator=S.next().charAt(0);
switch(operator)
{
case '+':System.out.println("add: "+(n1+n2));
break;
case '-':System.out.println("sub: "+(n1-n2));
break;
case '*':System.out.println("mult: "+(n1*n2));
break;
case '%':if (n1>n2)
System.out.println("mod:"+(n1%n2));
else
System.out.println("mod:"+(n2%n1));
break;
case '/':if(n1>n2)
System.out.println("div:"+(n1/n2));
else
System.out.println("div:"+(n2/n1));
break;
default:System.out.println("incorect option");
return;
}
}
}
Output:
S:\note java>javac AO.java
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 Grade.java
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 java.util.*;
class shortlist{
public static void main(String arg[]){
Scanner S=new Scanner(System.in);
System.out.print("enter students:");
int n=S.nextInt();
student obj[]=new student[n];
for(int i=0;i<n;i++){
obj[i]=new student();
System.out.println("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(System.in);
System.out.println("enter name :");
String name =S.nextLine();
System.out.println("enter percentage :");
per=S.nextInt();
System.out.println("enter backlogs:");
BL=S.nextInt();
System.out.println("enter testmarks :");
TM=S.nextInt();
if(per>=student.mp && BL==0 && TM>=student.mt)
System.out.println("ELIGIBLE");
else
System.out.println("REGECTED");
}
}
Output:
S:\note java>javac shortlist.java
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 Salary.java
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 java.util.
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
priorities.it 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 java.IO.*;
class Readtest
{
public static void main(String[] args)
{
try
{
File fl = new File("d:/myfile.txt");
BufferedReader br = new BufferedReader(new FileReader(fl)) ;
String str;
while ((str=br.readLine())!=null)
{
System.out.println(str);
}
br.close();
fl.close();
}
catch(IOException e) {
e.printStackTrace();
}
}
}
import java.IO.*;
class WriteTest
{
public static void main(String[] args)
{
try
{
File fl = new File("d:/myfile.txt");
String str="Write this string to my file";
FileWriter fw = new FileWriter(fl) ;
fw.write(str);
fw.close();
fl.close();
}
catch (IOException e)
{ e.printStackTrace(); }
}
}
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 System.in.
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 System.out.
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 System.err.
import java.io.*;
System.out.println(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 com.javatpoint;
2. import java.io.*;
3. public class BufferedReaderExample {
4. public static void main(String args[])throws Exception{
5. FileReader fr=new FileReader("D:\\testout.txt");
6. BufferedReader br=new BufferedReader(fr);
7.
8. int i;
9. while((i=br.read())!=-1){
10. System.out.print((char)i);
11. }
12. br.close();
13. fr.close();
14. }
15. }
16.
17.import java.io.BufferedInputStream;
18.import java.io.FileInputStream;
19.class Main {
20. public static void main(String[] args) {
21. try {
22. FileInputStream file = new FileInputStream("input.txt");
23. BufferedInputStream input = new BufferedInputStream(file);
24. int i = input .read();
25. while (i != -1) {
26. System.out.print((char) i);
27. i = input.read();
28. }
29. input.close();
30. }
31. catch (Exception e) {
32. e.getStackTrace();
33. }
34. }
35.}
String Tokenizer:
java.util.StringTokenizer class allows you to break a string into tokens.
import java.util.StringTokenizer;
public class Simple{
public static void main(String args[]){
StringTokenizer st = new StringTokenizer("my name is khan"," ");
while (st.hasMoreTokens()) {
System.out.println(st.nextToken());
}
}
}
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{
sb.append("Java");
System.out.println(sb);
Output:Hello java
Constructors:
Java InetAddress class:
It represents an IP address. The java.net.InetAddress class provides methods to get the
IP of any host name.
Method names:
getHostName();
getHostAddress();
1. import java.util.*;
2. class TreeMap1{
3. public static void main(String args[]){
4. TreeMap<Integer,String> map=new TreeMap<Integer,String>();
5. map.put(100,"Amit");
6. map.put(102,"Ravi");
7. map.put(101,"Vijay");
8. map.put(103,"Rahul");
9.
10. for(Map.Entry m:map.entrySet()){
11. System.out.println(m.getKey()+" "+m.getValue());
12. }
13. }
14. }
Output:100 Amit
101 Vijay
102 Ravi
103 Rahul
1. import java.io.*;
2. public class ReaderExample {
3. public static void main(String[] args) {
4. try {
5. Reader reader = new FileReader("file.txt");
6. int data = reader.read();
7. while (data != -1) {
8. System.out.print((char) data);
9. data = reader.read();
10. }
11. reader.close();
12. } catch (Exception ex) {
13. System.out.println(ex.getMessage());
14. }
15. }
16. }
1. import java.io.*;
2. public class WriterExample {
3. public static void main(String[] args) {
4. try {
5. Writer w = new FileWriter("output.txt");
6. String content = "I love my country";
7. w.write(content);
8. w.close();
9. System.out.println("Done");
10. } catch (IOException e) {
11. e.printStackTrace();
12. }
13. }
14. }
Output:done
1. import java.util.*;
2. import java.util.stream.*;
3. public class SortListExample1
4. {
5. public static void main(String[] args)
6. {
7. //returns a list view
8. List<String> slist = Arrays.asList("Tanu", "Kamal", "Suman", "Lucky", "Bunty", "A
mit");
9. List<String> sortedList = slist.stream().sorted().collect(Collectors.toList());
10. sortedList.forEach(System.out::println);
11. }
12. }
Output:-
#Sun Aug 24 13:34:24 IST 2014
password=Codingeek
database=localhost
username=Codingeek
1. import java.io.*;
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("f.txt");
9. ObjectOutputStream out=new ObjectOutputStream(fout);
10. out.writeObject(s1);
11. out.flush();
12. //closing the stream
13. out.close();
14. System.out.println("success");
15. }catch(Exception e){System.out.println(e);}
16. }
17. }