Java Programming

what is java?

java  is a high level programming language and  java is a platform independent
what is platform independent?
irrespective of the  operating system we can run the java programs.

features of java

1.simple
2.robust
3.secure
4.portable                                                            
5.object oriented
6.platform independent
7.distributed
8.multithread
9.dynamic

Abstraction
 1.abstraction  is nothing but getting the relevant information
Encapsulation
  2.encapsulation  wrapping the one(or)more components together.
Polymorphism
polymorphism  single entity with different behaviours.
      Inheritance
     inheritance  aquring the base class to data members and member functions into the derived class.

structure of a  java program

class demo
{
public static void main(string args[])
{
system.out.println("welcome to java class");
}
}
variables: 

 variable are used to store the data values ,it will change the values during the execution of a program.it may take different values at different times during the execution of a program.
it is a name given to a temporary memory location. memory allocation is done at the time of running the program
variable names may consist of
1.alphabets
2.digits
3.underscore etc…

syntax:

 type var_name
  int x;
  float y;
char c1,c2;
initialization

varname=value;
  n=20;
 m=10;

declaration:

 type  varname=value;
int m=5;
int n=10;
constants:

constants are fixed valued it will  not change the values during the execution of a program.
constants are two types

1.numeric constants:these are two types :

i.int: refers to a sequence of digits without a decimal point
ii.real:with a decimal point

2.character constants: these are two types

i.single characters(enclosed within single quotes ex:’j’,’5’)
ii.string characters(enclosed within double quotes ex:”java”,”lang”)

data types:
   
data types: are two types

1.primitive data types

  • byte
  • short
  • int
  • float
  • long
  • double
2.user defined data types
  • arrays
  • structures
  • functions
  • pointers
read and write operations in java

import java.util.*;
class add1
{
public static void main(string args[])
{
int v1,v2;
system.out.println("v1 value is");
scanner s = new scanner(system.in);
v1=s.nextint();
system.out.println("v2 value is");
v2=s.nextint();
int v3=v1+v2;
system.out.println("addition of v1+v2is"+v3);
}
}

operators:

operators are used to do the mathematical calculations
types of operators
1.arithmetic operators
2.logical operators
3.relational operators
4.conditional operators

introduction of decision making

a java program is a set of statements, when executed sequentially in order decision making
decision making or control statements:
1.if else statement
2.switch statement
syntax: if statement
if(test condition)
{
statement1;
}
statement2;

if- else statement

if(test condition)
{
statement1;
}
else
{
statement2;
}
nested if:

if(test condition1)
{
if(test condition2)
{
statement1;
}
else
{
statement2;
}
}
else
{
statement3;
}

switch statement:

if number of alternatives increases then the program becomes difficult to read and follow.
it may confuse even the designer of a program to avoid this condition we have switch statement.
syntax:
switch(expression)
{
case value1:
block
break ;
case value2:
block
break ;
case value3:
block
break ;
default:
block
break ;
}

introduction of loops:

the process of executing a block of code repeatedly is called as looping.
loops are 3 types

1.for loop
2.while loop
3. do-while loop

for-loop syntax

for (initialization;test condition;increment/decrement)
{
body of loop
}
ex: for(int i=0;i<=10;i++)

if the condition is true the body of the loop is executed otherwise loop is terminated and the execution continues with the statement.

while

it is used to execute a set of statements repeatedly as long as the given condition is true.
syntax
 while(test condition)
 {
 statements;  // body of the loop
 }

do - while

this statements execute a set of statements as long as the condition is true
this is similar to while loop, but the difference is ,this loop will execute the statements atleast once.
syntax
do
{
statements; // body of the loop
}
while(condition)

arrays:

array is a set of homogeneous or related data items that share a common name
ex: std marks[20]
represents the mark of 20 students.when the complete set of values is reffered to as an array.
the individual value are called elements
array can be of any variable type.

types of array

1.one dimensional array

declaration of array
type arrayname[];
int num[];
creation of array
arrayname = new type[size];
emp=new int[5];

2. two dimensional array syntax:

   type arrayname[] [];
   int table[] [];

Example on arrays in Java:

import java.util.*;
class aray1
{
public static void main(string args[])
{
scanner s=new scanner(system.in);
int marks[]= {20,10,60,30,40};
string name[]={"ram","rahem","robo","sita","geeta"};
system.out.println("enter u r roll no");
int rno=s.nextint();
int x=marks[rno];
if(x>40)
system.out.println("mr"+"\t"+ name[rno]+"\t"+"u r marks are"+"\t"+ marks[rno]+"and  u r passed");
else
system.out.println("mr"+"\t"+name[rno]+"\t"+"u r marks are"+"\t"+ marks[rno]+"\t"+" sorry u have failed");
}
}
//
import java.util.*;
class array2
{
public static void main(string args[])
{
scanner s=new scanner(system.in);
int costs[][][]=new int[3][4];
costs[][]={{20,10,60,30,40},{223,345,589,267,954},{34,56,78,89,30}};
system.out.println("1.soap 2.paste 3.deo");
system.out.println("enter your choice");
int bill, n;
int x=s.nextint();
switch(x)
{
case 1:
system.out.println("1.lux 2.rexona 3.rin");
system.out.println("enter value");
int x=s.nextint();
bill=cost[x][y]*n;
break;
case 2:
system.out.println("1.closeup 2.colgate 3.pepsodent");
system.out.println("enter value");
int x=s.nextint();
bill=cost[x][y]*n;
break;
case 3:
system.out.println("1.poison 2.axe 3.wwwn");
system.out.println("enter value");
int x=s.nextint();
bill=cost[x][y]*n;
break;
               
method:

a method is an operation on a particular object. an object is an instance of a class. when we define a class we define its member variables and its methods. for each method we need to give a name, we need to define its input parameters and we need to define its return type. we also need to set its visibility(private, package, or public). if the method throws an exception, that needs to be declared as well.
the syntax of method definition is

class myclass
{
 ...
    public returntype methodname( paramonetype param1, paramtwotype param2 ) throws exceptionname
    {
      returntype rettype;
      ...
      return rettype;
    }
 ...
}

Method example in java

class exam
{
int a;
int b;
void show()
{
a=10;
b=20;
}
void display()
{
system.out.println("a value is"+a);
system.out.println("b value is"+b);
}
}
class method1
{
public static void main(string args[])
{
exam e =new exam();
e.show();
e.display();
}
}
class: class is a combination of data members and member functions.
object: object is a instance of a class.

Example on parseint in Java:

class add1
{
public static void main(string args[])
{
int a,b;
a=integer.parseint(args[0]);
b=integer.parseint(args[1]);
int c=a+b;
system.out.println("addition is"+c);
}
}
ex1:
class demo
{
public static void main(string args[])
{
int a;
a=integer.parseint(args[0]);
float b=float.parsefloat(args[1]);
string name=args[2];
system.out.println("a value is"+a+"\n"+"b value is"+b+"\n"+"u r name is"+name);
}
}
ex2:
class demo1
{
void bill(int x)
{
if(x>10000)
x=x*80/100;
else
x=x*70/100;
system.out.println("pay u r bill"+x);
}
public static void main(string args[])
{
system.out.println("welcome to shopping");
demo1 d=new demo1();
int amt=integer.parseint(args[0]);
d.bill(amt);
system.out.println("thank u for shopping");
}
}
ex3:
class demo2
{
void booking(int n)
{
int tot=50;
int tcost=100;
if(n<=tot)
{
int bill=n*tcost;
system.out.println("i want to buy tickets"+"\t"+n+"\n"+"pay u r bill rs."+"\t "+bill);
}
else
{
system.out.println("sorry tickets are not available");
}
}
public static void main(string args[])
{
int n=integer.parseint(args[0]);
demo2 d =new demo2();
d.booking(n);
}}

Example on switch in Java:

class switch1
{
public static void main(string args[])
{
char choice;
system.out.println("enter u r choice");
system.out.println("c ..lang");
system.out.println("c++.. lang");
system.out.println("java.. lang");
system.out.flush();
try
{
switch(choice=(char) system.in.read())
{
case 'c':system.out.println(" u have selected c the cost :1000");
break;
case 'k':system.out.println("u have selected c++ the cost :2000");
break;
case 'j':system.out.println("u have selected java the cost:3000");
break;
default:system.out.println("invald");
}
}
catch(exception e)
{
system.out.println("exce");
}
}
}
 Program on switch using scanner in Java

import java.util.*;
class res
{
int ch;
scanner s=new scanner(system.in);
void mem()
{
system.out.println("1.sil 2.gold 3.dia");
system.out.println("enter u r choice");
ch=s.nextint();
switch(ch)
{
case 1:system.out.println(" u have selected silver card");
break;
case 2:system.out.println("u have selected gold card");
break;
case 3:system.out.println("u have selected diamond card");
break;
default:system.out.println("invald");
}
}}
class switch2
{
public static void main(string args[])
{
res r=new res();
r.mem();
}
}
inheritance:

this is a property of acquiring things from one class to the other this concept is used or developed to reuse the existing code.
“extends” is a keyword which is used to inherit the class.

Example on inhreritance in Java

class father
{
father()
{
system.out.println("iam father");
}
class child extends father
{
child()
{
system.out.println("iam child");
}
}
class inher
{
public static void main(string args[])
{
father a=new father();
child c=new child();
}
}
}

Example on inheritance in Java

class base
{
void show()
{
system.out.println("iam base show");
}
void display()
{
system.out.println("iam display");
}
}
class derived extends base
{
void show()
{
system.out.println("iam derived show");
}
void get()
{
system.out.println("iam get");
}
}
class inherit1
{
public static void main(string args[])
{
derived d=new derived();
d.show();
d.display();
d.get();
}

}


Example on scanner: find out fathe salary in Java

import java.util.*;
class Salary2
{
public static void main(String args[])
{
int netsalary,schoolfee;
int finalsalary;
scanner s =new scanner(System.in);
System.out.println("enter netsalary");
netsalary =s.nextint();
System.out.println("enter school fee");
schoolfee=s.nextint();
finalsalary=netsalary-schoolfee;
System.out.println("final salary"+finalsalary);
}
}
Program example on scanner:

import java.util.*;
class bill1
{
public static void main(string args[])
{
scanner s = new scanner(system.in);
int pcost,bcost;
int bill;
system.out.println("enter the pencost");
system.out.println("enter the bookcost");
pcost=s.nextint();
bcost=s.nextint();
bill= pcost+bcost;
system.out.println("final bill"+bill);
}
}
example on scanner

import java.util.*;
class Bookcost
{
public static void main(String args[])
{
int bcost,bill;
Scanner s=new Scanner(System.in);
System.out.println(" enter the cost of the book");
bcost=s.nextInt();
bill=bcost*80/100;
System.out.println("your bill is"+bill);
}
}
example on arrays:

import java.util.*;
class Array1
{
public static void main(String args[])
{
Scanner s=new Scanner(System.in);
int marks[]= {20,10,60,30,40};
string name[]={"ram","rahem","robo","sita","geeta"};
System.out.println("enter u r roll no");
int rno=s.nextInt();
int x=marks[rno];
if(x>40)
System.out.println("mr"+"\t"+name[rno]+"\t"+"u r marks are"+"\t"+ marks[rno]+"and  u r passed");
else
System.out.println("mr"+"\t"+name[rno]+"\t"+"u r marks are"+"\t"+ marks[rno]+"\t"+" sorry u have failed");
}
}

array

import java.util.*;
class aray2
{
public static void main(string args[])
{
scanner s=new scanner(system.in);
int marks[]= {20,10,60,30,40};
string name[]={"ram","rahem","robo","sita","geeta"};
system.out.println("enter u r roll no");
int rno=s.nextint();
int x=marks[rno];
if(x>40)
system.out.println("mr"+name[rno]+"u r"+ marks[rno]+"and passed");
else
system.out.println("mr"+name[rno]+"u r"+ marks[rno]+"and failed");
}
}
Example on array in Java

import java.util.*;
class aray3
{
public static void main(string args[])
{
scanner s=new scanner(system.in);
system.out.println("1.air 2.rail 3.bus 4.car");
system.out.println("enter ur choice no 1,2,3,4 ");
int x=s.nextint();
int cost[]={0,100,200,300,400};
system.out.println("enter how many tickets you want");
int n=s.nextint();
int tickets=cost[x]*n;
system.out.println("collect ur tickets"+tickets);
}
}

Example on function in Java

class fun1
{
void show()
{
system.out.println("i am show function");
}
public static void main(string args[])
{
fun1 f=new fun1();
f.show();
}
}

Example on for loop in Java

class for1
{
public static void main(string args[])
{
int n;
for(n=0;n<=10;n++)
{
system.out.println("......"+n);
}
}
}

Example on while in Java:

class while1
{
public static void main(string args[])
{
int count=1;
while(count<11)
{
system.out.println("count is"+count);
count++;
}
}
}

Example on dowhile in Java

class dowhile1
{
public static void main(string args[])
{
int count=5;
do
{
system.out.println("count is"+count);
count++;
}
while(count<=6);
}
}

Example on if  in Java

class if1
{
public static void main(string args[])
{
int a=4523,b=782,c=123;
system.out.println("largest value  is:");
if(a>b)
{
if(a>c)
{
system.out.println(a);
}
else
{
system.out.println(c);
}
}
else
{
if(c>b)
{
system.out.println(c);
}
else
{
system.out.println(b);
}
}
}
}

abstraction:


abstract function: 

if a functions signature is given and implementation part is not given then will call it as abstract function.
abstract functions  are defined with a keyword called “abstract” in front of a function.

abstract class:

if a class contain one or more abstract methods then the class is set to be abstract class.it may have implemented and unimplemented methods.
for abstract class we cannot create an object.
in abstract class it is not compulsory to define a method but it is compulsory to define in the class.

Example on abstraction in Java

abstract class demo
{
abstract void show();
             void display()
{
system.out.println("hello");
}
}                                         
class exam extends demo
{
void show()
{
system.out.println("welcome");
}
}
class ab
{
public static void main(string args[])
{
exam e=new exam();
e.display();
e.show();
}
}

interface:

interface is a collection of  unimplemented methods and final variables.
 the class can use the interface by implementing it.
1. implement is a keyword which is used by the class to implement an interface.
2. interface has only public as a access specifier.
3.the variable defined in interface is by default considered as final(whether you write “final” infront of a variable or not, it is a final)

and this variables are common to all the classes to which are implementing in it.

Example on interface in Java?

interface example
{
            void show();
            void display();
}
class demo implements example
{
public void show()
{
system.out.println("welcome");
}
public void display()
{
system.out.println("hello");
}
}
class inter
{
public static void main(string args[])
{
demo e=new demo();
e.display();
e.show();
}
}

constructor:

constuctor is a special method
defined with the same name of the class.
1.this will be called only once at the time of creating a class object.
2.this method will not have any return type.
3.this method will have only public access specifier.
4.this method will be invoke immediately after allocating the memory for the object and this is going to initiative all the data members of the class

syntax:
 
class classname
{
public classname(parameters)
{
}
}

types of constructors:
1.dummy constructor
2.default constructor or non param
3.parameterised
4.copy

overloading:

if we have a function in the base class and derived class with the same name but different no of parameters than this will also satisfy the conditions of overloading

Program on default constuctor in Java

class exam
{
int a,b;
public exam()
{
a=10;
b=10;
}
void show()
{
system.out.println("a value is"+a);
system.out.println("b value is"+b);
}
}
class decons
{
public static void main(string args[])
{
exam e=new exam();
e.show();
}
}

Example on constructor overloading in Java

class bank
{
int acno,bal;
bank()
{
acno=1;
bal=0;
}
bank(int z)
{
acno=z;
bal=0;
}
bank(int p,int y)
{
acno=p;
bal=y;
}
void show()
{
system.out.println("my ac no"+acno+"\n"+"balance"+bal);
}
}
class constovload1
{
public static void main(string args[])
{
bank b=new bank();
bank b1=new bank(2);
bank b2=new bank(3,10000);
b.show();
b1.show();
b2.show();
}
}
overriding

if we have a function with the same name in the base class and derived class with the same number of parameters and same type of parameters then derived class is going to override the base class function this is called overriding.

Example on overriding in Java

class base
{
void show()
{
system.out.println("iam base show");
}
void display()
{
system.out.println("iam display");
}
}
class derived extends base
{
void show()
{
system.out.println("iam derived show");
}
void get()
{
system.out.println("iam get");
}
}
class override1
{
public static void main(string args[])
{
derived d=new derived();
d.show();
d.display();
d.get();
}
}

exceptions

exception is a error.
compiler: converts the high level language into machine code.
error: 1.abnormal termination of a programme.
2.causing mistakes to a programme.
errors are 2 types

1.compile time error
2.run time error

compile time error:

these errors are encounter when we are trying to translate or during the conversion of high level language to machine code.these are generally  syntactical or grammatical errors.
these are cought /found during the compilation of program.

run time error

run time errors  which will encounter during the execution of the program due to logical errors.

Exception handling:

the mechanism of handing exception is called exception handing.
exception handing is performed or done using the following keywords.
1.try
2.catch
3.throw
4.throws
5.finally
try:within the try block we write the statements that may or maynot arise to an exception but possibility of arising the exception.
note:a single statement or a try block can raise more than one exception at a time .
so to handle it we will be writing multiple catches in a single try.
catch:catch block will provide a solution or an alternative if the error occurred in the try block.
note: when more than one exception occurring in a single instance ,then whichever the catch block is going to take than that is going to handle.
    if one catch block is already handled than remaining catch blocks will not verify.
throw:is a keyword which is used to raise an exception by the programmer.
usage of the throw: the programmer should know what exception will occur at what time,here the user/programmer will handle the exception in throw.
throws: jvm will handle the throws
this provide us a mechanism where we don like to provide an alternative but to throw an exception.
finally: is a keyword irresepective of occurance of exception the finally block will execute.
shouldnot worry whether the exception occurred or not.

generalize exceptions:

1.in a program you did not define the withdraw() but your calling it is an exception.
2.class not define,but calling exception.
3.gave 10 values calling 11 values is an exception.
4.gave string but storing int is an exception
  1. class not found exception
  2. arithmetic  exception
  3. null pointer exception
  4. number format exception
  5. out of memory exception
  6. stack over flow exception
  7. array index out of bounds exception
  8. array store exception
checked exception:

this will handled by the programmer not by jvm.
these exceptions are explicitly handled the code it self with the help of try and catch block.
checked exceptions are extended from the package called
java.lang.exception;

unchecked exception:

this will handled by the jvm not by the programmer.
unchecked exceptions are extended from the package called
java.lang.uncheckedexception;

 program on try catch block in Java

import java.util.*;
class try1
{
public static void main(string args[])
{
scanner s= new scanner(system.in);
system.out.println("enter a value");
int a=s.nextint();
system.out.println("enter b value");
int b=s.nextint();
try
{
int c=a/b;
system.out.println("c value is "+c);
}
catch(exception e)
{
system.out.println("invalid no"+e);
}
system.out.println("thank u");
}
}

program on try catch block in Java

import java.util.*;
class try2
{
public static void main(string args[])
{
int a[]={0,10,20,30};
scanner s= new scanner(system.in);
system.out.println("enter n value");
int n=s.nextint();
system.out.println("enter b value");
int b=s.nextint();
try
{
int c=a[n]/b;
system.out.println("c value is "+c);
}
catch(arithmeticexception e)
{
system.out.println("invalid no"+e);
}
catch(arrayindexoutofboundsexception e)
{
system.out.println("not valid"+e);
}
}
}

Example  program on throw in Java

import java.util.*;
class exam
{
void show() throws arithmeticexception
{
scanner s= new scanner(system.in);
system.out.println("enter a value");
int a=s.nextint();
system.out.println("enter b value");
int b=s.nextint();
int c=a/b;
system.out.println("c value is "+c);
}
}
class throw1
{
public static void main(string args[])
{
exam e=new exam();
e.show();
}
}

Example on program  on finally in Java

class finally1
{
public static void main(string args[])
{
int i=0;
string box[]={"pen","book","pencil"};
while(i<3)
{
try
{
system.out.println(box[i]);
}
catch(arrayindexoutofboundsexception e)
{
system.out.println("exception"+e);
i++;
}
finally
{
system.out.println("this is finally");
}
i++;
}
}
}
thread:

thread  is a light weight process which can work independently without effecting the remaining process.

process: 

process is a combination of threads


multiprocessor
Code
code
Stack
stack
Data
processor
code
 stack
 data

             



















life cycle of a thread


thread priorities

minimum -1
maximum-10
normal-5

setting thread priorities

thread.max_priority
thread.min_priority
thread.normal_priority

difference between wait() and sleep()

wait(): it is used to wait the thread until it gets notification
sleep():if the time slot is completed it will go back to the thread.

synchronization:

two to more threads are trying to access the same method at the same point of time then it leads to synchronization .if that particular method is declared as synchronized only one thread can access it at a time.another thread can access it only if the first thread task is complete.

yield:

it causes the currently execution thread to pause the execution temporarily and gives the chance for remaining threads of same priority to execute.

Program on thread in Java

class a extends thread
{
public void run()
{
for(int i=1;i<=5;i++)
system.out.println(" value is "+i);
}
public void start()
{
system.out.println("iam start in thread");
run();
}
}
class thread1
{
public static void main(string args[])
{
a t=new a();
t.start();
}
}

program on multiple threads in Java

class a extends thread
{
public void run()
{
for(int i=1;i<=5;i++)
{
system.out.println(" thread a "+i);
}
system.out.println(" exit from a");
}
}
class b extends thread
{
public void run()
{
for(int i=1;i<=5;i++)
{
system.out.println(" thread b "+i);
}
system.out.println(" exit from b");
}
}
class c extends thread
{
public void run()
{
for(int i=1;i<=5;i++)
{
system.out.println(" thread c "+i);
}
system.out.println(" exit from c");
}
}
class thread2
{
public static void main(string args[])
{
a a=new a();
b b=new b();
c c=new c();
a.start();
b.start();
c.start();
}

Program on thread priorities in Java

class a extends thread
{
public void run()
{
for(int i=1;i<=10;i++)
{
try
{
system.out.println("a value is "+i);
}
catch(exception e)
{
system.out.println("exception"+e);
}
}
}
}
class b extends thread
{
public void start()
{
for(int i=1;i<=10;i++)
{
try
{
system.out.println(" b the values are"+i);
}
catch(exception e)
{
system.out.println("exception"+e);
}
}
}
}
class threadprio
{
public static void main(string args[])
{
a a =new a();
b b=new b();
b.setpriority(thread.max_priority);
a.setpriority(thread.min_priority);
system.out.println("started a thread ");
a.start();
system.out.println("started b thread");
b.start();
system.out.println("end of main thread");
}
}

Program on yield method in Java

class mythread extends thread
{
public void run()
{
for(int i=1;i<=5;i++)
{
system.out.println("child thread");
thread.yield();
}
}
}
class yield
{
public  static void main(string args[])
{
mythread t=new mythread();
t.start();
for(int i=1;i<=5;i++)
{
system.out.println(" main thread");
}
}
}

Example on sleep method in Java

class a extends thread
{
public void run()
{
for(int i=1;i<=10;i++)
{
try
{
system.out.println(" a thread"+i);
thread.sleep(1000);
}
catch(exception e)
{
system.out.println("exception"+e);
}
}
}
}
class b extends thread
{
public void start()
{
for(int i=1;i<=10;i++)
{
try
{
system.out.println("b thread"+i);
thread.sleep(100);
}
catch(exception e)
{
system.out.println("exception"+e);
}
}
}
}
class threadsleep
{
public static void main(string args[])
{
a a=new a();
b b=new b();
a.start();
b.start();
}
}
 

 
                                                      For Part2  Click here

For Frequently asked Java Programs Click here
                   

Thanks for visiting this blog. How is the content?. Your comment is great gift to my work. Cheers.

No comments:

Post a Comment