Core Java

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 42

Methods- an user defined methods could be classified into following categories-

1. Method with no argument & no return value

2. Method with argument but no return value

3. Method with argument and return value

4. Method with no argument but return value

The Genral form of a Method will be-

access_specifier return_type method_name(argument)

body of the method

Note- For accessing the member of a class you must create the object of that class like the
following-

class objectname=new classname();

objectname.methodname();

1. Method with no argument & no return value- if you want to perform any static operation,
then use such type of method.

ex.

WAP which generates the following output-

**************************************************************************

Sushant T College

**************************************************************************
**************************************************************************

Sol-

class logic

public void Line()

int i;

for(i=1;i<=70;i++)

System.out.print("*");

System.out.println();

class test

public static void main(String args[])

logic obj=new logic();

obj.Line();

System.out.println("\t\t\tSushant IT College");

obj.Line();

obj.Line();
}

______________________________________________________________________________
___

2. Method with argument but no return value- if you want to perform any dynamic operation
according to given value, but the oocurance of result is more than one then you can use such
type of method.

ex.

WAP which generates the following output-

**************************************************************************

Sushant T College

&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&

^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

Sol-

class logic

public void Line(String ch)

int i;

for(i=1;i<=70;i++)

System.out.print(ch);

System.out.println();
}

class test

public static void main(String args[])

logic obj=new logic();

obj.Line("*");

System.out.println("\t\t\tSushant IT College");

obj.Line("&");

obj.Line("^");

Que- Create a Method named as table() which contains a number as argument & print the
table of given number.

_________________________________________________________

3. Method with argument and return value- if you want to perform any dynamic operation
by a given value & result is an aggregate value then you can use such type of methods.

Que- Create a Method named as max() which contains three numbers as argument & return
the largest one.

Sol-1

class logic

public int max(int a,int b,int c)

{
int m;

if(a>b && a>c)

m=a;

else if(b>a &&b>c)

m=b;

else

m=c;

return m;

class test

public static void main(String args[])

logic obj=new logic();

int res=obj.max(100,20,4);

System.out.println("Largest : "+res);

Que- Create a method named as fact() which contains a number as argument & return the
factorial of that number.

Que- Create a method named as power() which contains base number(x) and power
number(n) as argument & return x to the power n.
_______________________________

4. Method with no argument but return value- Such Kinds of method works on the members
of class-

for ex.

class logic

int a,b,c;

public void get(int x,int y,int z)

a=x;

b=y;

c=z;

public int max()

int m;

if(a>b && a>c)

m=a;

else if(b>a &&b>c)

m=b;

else

m=c;
return m;

public void show()

System.out.println("Largest : "+max());

class test

public static void main(String args[])

logic obj=new logic();

obj.get(100,20,4);

obj.show();

_______________________________________________________________________

Method Overloading-It is the practical implementation of Polymorphism. If class contains


more than one method with same name but different argument, then this term is known as
method overloading.

Que-Create an overoaded method named as reverse() which reverse() the digits of a number
or characters of a string as per the given argument.
Que- Create an overloaded method named as lcm() which return the lcm of either 2 , 3 or 4
given values.

Sol-2

class logic

int m,i,res;

public int lcm(int a,int b)

m=a*b;

for(i=1;i<=m;i++)

if(i%a==0 && i%b==0)

res=i;

break;

return res;

public int lcm(int a,int b,int c)

m=a*b*c;

for(i=1;i<=m;i++)
{

if(i%a==0 && i%b==0 && i%c==0)

res=i;

break;

return res;

public int lcm(int a,int b,int c,int d)

m=a*b*c*d;

for(i=1;i<=m;i++)

if(i%a==0 && i%b==0 && i%c==0 && i%d==0)

res=i;

break;

return res;

}
class test

public static void main(String args[])

logic obj=new logic();

System.out.println("LCM Among Two Values :"+obj.lcm(3,5));

System.out.println("LCM Among Three Values :"+obj.lcm(2,4,6));

System.out.println("LCM Among Two Values :"+obj.lcm(4,6,8,5));

______________________________________________________________________________
_______

Constructors- They are used for initilizing the members of a class. the propertoes of
constructors will be-

1. The name of constructor must be same as the name of class.

2. They did not return any value not even void.

3. They called automatically when the object of the class is created.

Types of Constructors

1. Default Constructors

2. Parametrized Constructors

3. Overloaded Constructors

1. Default Constructors- If a constructors did not contains any argument then it is known as
default constructors.
eg.

class cons

String name;

int age;

public cons()

name="Bzar";

age=24;

public void show()

System.out.println("Name : "+name);

System.out.println("Age : "+age);

class test

public static void main(String args[])

cons obj=new cons();

obj.show();

}
___________________________________________________________

2. Parametrized Constructors- The constrctors which takes the arguments are known as
parametrized constructors. the value of argument must be passed at the time of object
creation.

class cons

String name;

int age;

public cons(String n,int a)

name=n;

age=a;

public void show()

System.out.println("Name : "+name);

System.out.println("Age : "+age);

class test

{
public static void main(String args[])

cons obj=new cons("Quamar",25);

obj.show();

______________________________________________________________________________
__

3. Overloaded Constructors - If a class contains more than one construtor then this term is
known as overloaded constructor.

class Line

int i;

public Line()

for(i=1;i<=70;i++)

System.out.print("*");

System.out.println();

public Line(String ch)

{
for(i=1;i<=70;i++)

System.out.print(ch);

System.out.println();

class test

public static void main(String args[])

Line obj;

System.out.println("First Line Style");

obj=new Line();

System.out.println("Second Line Style");

obj=new Line("&");

_________________________________________________________

Inheritance- This is the concept of reusability.

for definiting a sub class you must follow the folliwng syntax-
class subclassname extends superclassname

body of the class

Note - remember only public member of super class inherited in sub class.

Syntax for creating sub class

class subclassname extends superclassname

body of the class

class first

public void one()

System.out.println("First Method of The Super Class Class");

privateone();

private void privateone()

System.out.println("private Method of The Super Class Class");

}
class sec extends first

public void two()

System.out.println(" Method of The Sub Class Class");

class test

public static void main(String args[])

sec obj=new sec();

obj.one();

obj.two();

________________________________________

using this keyword- We can use two variations of this keyword, these are-

1. this statement

2. this() method

1. this statement- It reference the member of same class.


class thdemo

int a,b;

public void get(int a,int b)

this.a=a;

this.b=b;

public void put()

System.out.println("First Value : "+a);

System.out.println("Second Value : "+b);

class test

public static void main(String args[])

thdemo obj=new thdemo();

obj.get(10,20);

obj.put();

}
}

____________________________________________________

this () method- It is used for calling the constructor of class inside the another constructor of
same class.

class thdemo

public thdemo()

System.out.println("First Constructor");

public thdemo(int n)

this();

System.out.println("Second Constructor");

class test

public static void main(String args[])

thdemo obj=new thdemo(10);

}
}

___________________________________________________________________________

using super keyword- like this we can also use two variations of super keyword-

1. super statement

2. super method

1. super statement - this statement is used for accessing the member of super class inside sub
class.

class first

int a,b;

public void get(int a,int b)

this.a=a;

this.b=b;

class sec extends first

int a,b;

public void set()

this.a=super.a;

this.b=super.b;
}

public void show()

System.out.println("First Value : "+a);

System.out.println("Second Value : "+b);

class test

public static void main(String args[])

sec obj=new sec();

obj.get(10,20);

obj.set();

obj.show();

________________________________

2. super() method- It is used for calling the constructor of super class inside the sub class.

class first

{
public first()

System.out.println("First Constructor");

public first(int n)

System.out.println("Second Constructor");

class sec extends first

public sec()

super(10);

System.out.println("Constructor of Sub Class");

class test

public static void main(String args[])

sec obj=new sec();


}

_______________________________________________________________

static keyword- we use 3 variations of static keyword, These are-

1. static variable

2. static methods

3. static class

1. static variable- The are known as class level variables & they share a single copy of the
variable to each object of a class.

class stdemo

static int num;

public void set()

num++;

public void get()

System.out.println("Value : "+num);

class test

{
public static void main(String args[])

stdemo obj1=new stdemo();

stdemo obj2=new stdemo();

stdemo obj3=new stdemo();

obj1.set();

obj2.set();

obj3.set();

obj1.get();

obj2.get();

obj3.get();

______________________________________________________________________________
______

static methods-if you declare a method as static then you can call the particular method along
with the class name without creating the object.

class stdemo

public static void msg()

System.out.println("Hi , i m Static Method");

}
class test

public static void main(String args[])

stdemo.msg();

______________________________________________

static class - if a class contains the static members then it is known as static class.

method overriding- if we define a method is sub class which signature exactly mathched with
any other method of super class , then this term is known as method overriding.

class first

public void msg()

System.out.println("This is Method of Super Class");

class sec extends first

{
public void msg()

super.msg();

System.out.println("This is Method of Sub Class");

class test

public static void main(String args[])

sec obj=new sec();

obj.msg();

______________________________

using final- we can use 3 variations of final keyword-

1. final variable

2. final method

3. final class

1. final variable- if you declare a variable as final then you can not change the value of that
variable during execution of the program. Means it will be a constant variable.

class test
{

public static void main(String args[])

final int a=10;

System.out.println(a);

//a=20;

//System.out.println(a);

______________________________

2. final method - if you define a method as final then you can not override the particular
method.

class first

final public void msg()

System.out.println("This is Method of Super Class");

class sec extends first

public void msg()

super.msg();
System.out.println("This is Method of Sub Class");

class test

public static void main(String args[])

sec obj=new sec();

obj.msg();

_________________________

3. final Class- if you define a class as final means you can not inherit the particular class

final class first

public void msg()

System.out.println("This is Method of Super Class");

class sec extends first

{
public void msg()

super.msg();

System.out.println("This is Method of Sub Class");

class test

public static void main(String args[])

sec obj=new sec();

obj.msg();

_______________________________________________________

interface & abstract class- They are used for desining the model of a system.

interface- it contains the list of unimplemented methods & defines the responsibility of a
class.

Syntax

interface interfacename

method prototype-1
method prototype-2

___________________

___________________

for implementing the interface on the class-

class classname implements interfacename

body of the class

Note - if you implements an interface in your class then you must override all the methods
whatever is declared inside the interface.

interface qamarwork

public boolean palindrome(int n);

public int reverse(int n);

class qamar implements qamarwork

public int reverse(int n)

int rev=0,r;

while(n>0)
{

r=n%10;

rev=rev*10+r;

n=n/10;

return rev;

public boolean palindrome(int n)

return n==reverse(n)?true:false;

class test

public static void main(String args[])

qamar obj=new qamar();

if(obj.palindrome(121))

System.out.println("Number is Palindrome");

else

System.out.println("Number is Not Palindrome");

}
}

__________________________________________

abstract class- it same like interface but difference is that it contains implemented &
unimplemented methods both. and methods which will be unimplemented must define
asbtract methods. we inherit the abstract class but could not create the object of abstract
class.

abstract class qamarwork

abstract boolean palindrome(int n);

public int reverse(int n)

int rev=0,r;

while(n>0)

r=n%10;

rev=rev*10+r;

n=n/10;

return rev;

class qamar extends qamarwork

{
public boolean palindrome(int n)

return n==reverse(n)?true:false;

class test

public static void main(String args[])

qamar obj=new qamar();

if(obj.palindrome(121))

System.out.println("Number is Palindrome");

else

System.out.println("Number is Not Palindrome");

Difference between abstract class and interface


Abstract class and interface both are used to achieve abstraction where we can declare
the abstract methods. Abstract class and interface both can't be instantiated.

But there are many differences between abstract class and interface that are given
below.
Abstract class Interface

1) Abstract class can have abstract and non- Interface can have only
abstract methods. abstract methods. Since Java 8, it can
have default and static methods also.

2) Abstract class doesn't support multiple Interface supports multiple


inheritance. inheritance.

3) Abstract class can have final, non-final, Interface has only static and final
static and non-static variables. variables.

4) Abstract class can provide the Interface can't provide the


implementation of interface. implementation of abstract class.

5) The abstract keyword is used to declare The interface keyword is used to


abstract class. declare interface.

6) An abstract class can extend another Java An interface can extend another Java
class and implement multiple Java interfaces. interface only.

7) An abstract class can be extended using An interface can be implemented using


keyword "extends". keyword "implements".

8) A Java abstract class can have class Members of a Java interface are public
members like private, protected, etc. by default.

9)Example: Example:
public abstract class Shape{ public interface Drawable{
public abstract void draw(); void draw();
} }

Simply, abstract class achieves partial abstraction (0 to 100%) whereas interface achieves
fully abstraction (100%).

_______________________________________________________________
packages- It is like a folder which contains classes, and we can import them whenever is
required.

Steps for creating your own package.

1. create a folder in your system with the same name which you want for your package. for
eg opr

2. now open notepad & write program for package.

package opr;

public class qamar

public int reverse(int n)

int rev=0,r;

while(n>0)

r=n%10;

rev=rev*10+r;

n=n/10;

return rev;

public boolean palindrome(int n)

return n==reverse(n)?true:false;

}
}

3. svae your package inside the package folder.

4. now compile your package

5. now write a program for using the package

import opr.*;

class test

public static void main(String args[])

qamar obj=new qamar();

if(obj.palindrome(121))

System.out.println("Number is Palindrome");

else

System.out.println("Number is Not Palindrome");

6. Save your program. like c:\

7. now set path again, like the following-

set path=java_path;package_folder_path

8. now run your program

__________________________________________________________

Exception Handling-
In a program there may be 3 types of errors could be generated these are-

1. Compile time errors

2. Logical Errors

3. Run Time Errors

Compile time errors are traced by the compiler and without debuging this your
program could not execute.

Logical erros are occured due to invalid logic of the programmer and this could be
traced by a programmer.

Run Time Errors- they are known as execeptions and when they occured they terminated the
execution a program.

The exception handling is a techniqe which allows you form handling run time exceptions.

java provides a block named as try.. catch.. block which is used for handling any exeception.

Syntax

try

java code....

}catch(ExceptionClassName objectName)

Message/Action

finally

Message/Action
}

note - finally is an optional block which execute in each case either exception is occured or
not?

import java.util.*;

class test

public static void main(String args[])

Scanner sc=new Scanner(System.in);

int a,b,c;

System.out.print("Enter First Number :");

a=sc.nextInt();

System.out.print("Enter Second Number :");

b=sc.nextInt();

try{

c=a/b;

System.out.println("Result : "+c);

}catch(Exception e)

System.out.println("Problem in Divide");

finally

System.out.println("Bye..Bye");
}

System.out.println("Some Other Work");

Built-in Exception Classes- java provides a lot of built in exception classes, which are used for
handling the exception as per the exception type.

Classes Meaning

IOException When I/O related problems occur

ArithmeticException When number is / by 0

ArrayIndexOutOfBoundsException When we want to access an array element which is not


exist in the array

StringIndexOutOfBoundsException When we want to access a string element which is not


exist in the string

ClassNotFoundException When the used class is not found

NullPointerException if an object is used without initilizing

using single try with multiple catch- if you want to handle the exception according to their
exception type then you can use single try with multiple catch-

class exec

public static void main(String args[])

int i;

for(i=1;i<=3;i++)
{

try{

switch(i)

case 1:

int a=10,b=0;

System.out.println(a/b);

break;

case 2:

String s="Bzar";

System.out.println(s.charAt(10));

break;

case 3:

int arr[]=new int[30];

System.out.print(arr[80]);

break;

}catch(ArrayIndexOutOfBoundsException ae)

System.out.println("Array Related problem");

catch(StringIndexOutOfBoundsException se)

System.out.println("String Related problem");


}

catch(ArithmeticException e)

System.out.println("Number is / By 0");

________________________________________________________________________

using throws & throw statement-

throws - if you are not intrested to handle the run time exceptions then you can use throws
statement

import java.io.*;

class demo

public static void main(String args[]) throws IOException

InputStreamReader in=new InputStreamReader(System.in);

BufferedReader br=new BufferedReader(in);

int a,b,c;

System.out.print("Enter First Number :");

a=Integer.parseInt(br.readLine());

System.out.print("Enter Second Number :");

b=Integer.parseInt(br.readLine());
c=a+b;

System.out.println("Sum : "+c);

throw- it is used for throwing our own exception.

import java.util.*;

class ownexec

public void inrange(int n) throws Exception

if(n>=1 && n<=10)

System.out.println(n+" is a valid Value");

else

throw new Exception(n+" is not a valid Value");

class test

public static void main(String args[])

Scanner sc=new Scanner(System.in);

int num;
System.out.print("Enter Number :");

num=sc.nextInt();

try{

ownexec obj=new ownexec();

obj.inrange(num);

}catch(Exception e)

System.out.println("Error : "+e.getMessage());

_______________________________________________

You might also like