Sunteți pe pagina 1din 181

WELCOME TO J2SE

Prepared by
MANASH E B K.
ASST PROFESSOR

Department of IT.
CRR COLLEGE OF ENGG.
Core java
• Developed by james josling in sun
microsystem lab.
• Starting its called as OAK.
Disadvantages of Procedure oriented
programming
• Error finding difficulty.
• Updasion is difficult .
• Data freely moving all over program.
• Main importance is given to algorithm not
data.
• Reusability is not there.
• Not suitable to solve real world problems
Object oriented programming features

• Class
• Object
• Inheritance
• Polymorphism.
• Dynamic binding
• Message passing
class
• It is template of user defined data type.
• Class is logical entity.
• Class contains data members(variables) and
member function(methods).
• From class we can create number of objects.
• Syntax of class:
Class class_name{
Datamembers
Member functions}
Object
• Object is runtime entity.(object created while
Exicuting program)
• Object physically exist(like person , bench,
organigation)
• From class we create the objects.
• At this time memory allocated for data
members of class.
• Separate copy is created for each object.
object
• Syntax
• Class_name object name;
Object-name=new class-name();
• Or Class_name object name=new class-
name();
Inheritance
• Reusability.
• Existed class (base) we can inherit to another
class(child).
• advantage;
memory saved.
programmer effort also saved.
Uses key word extends keyword.
polymorphism
• Many forms
• Single function or operator used perform
differently in different instances.
• Example:
– Myself here I behave like trainer for java
– At home husband to my wife.
– father to my children.
Dynamic Binding
• Binding: Linking of function call with function
code.
• Dynamic Binding:
– Here Linking at runtime.
Message passing
• In oops object can Interact.
• One object can interact with other object by
message passing.
Difference between C and java
• Java is object oriented language, whereas c is
procedure oriented language.
• There is no pointers in java.
• There is no preprocessor directives in java.
• Java adds labeled break and countinue
statements.
• Java does not have sizeof and #define
statements.
Difference between C and java
• There is no structure and union in java.
• Java having class in place of structure with
added features.
• Java provides security to data by using
different access specifies(private , protected).
Difference between C++ and java
• Java does not have templates
• Java having garbage collectors.
• Java having interfaces.
• Java does not have multiple inheritance.
• Java having instanceof operators.
• No header files in java.
• No operator overloading in java.
Java features
• Platform independent.
• Portable.
• Compiled and interpreted.
• Simple , small , familier.
• Object oriented language.
• Robust and secure.
• Extensible.
Flavors of java
• J2SE :java standard edition contains java API.

• j2EE: java enterprise edition (servlet , EJB)

• j2ME: java Micro edition (embedded Systems


like mobile phone application related)
Why should we learn java
• To solve real world problems.
• Provides reusability facility.
• Takes care about serious runtime errors.
• Platform indepependentness.
• Portability.
• Easy Updating.
• Security.
Steps in writing java program
• File name should have extension like .java
• Should contain main method
– Public static void main(String Args[]).
Syntax of class structure
Class class_name
{
datamembers;
MemberFunction;

}
Class example
• Class Cse
• {
public static void main(String Args[])
{
System.out.println(“Hai CSE Guys”);
}
}
• Compilation of java program
Javac filename.java
• It generates Byte code like NameOfClass
contained main method with .class extension.
• This code is platform Independent we can
execute in different environment.
Interpreting
• Java classname.java
• Than it produce output on console.
• Line by line Executing.
JVM
• Byte code is interpreted by JVM.
• JVM platform dependent.
• JVM contain different class libraries
• JVM does the following tasks.
– Load code
– Verify code.
– Execute the code.
• JRE(java runtime environment)
– JVM+class libraries
JDK(Java Development Kit)
JRE + Class Libraries.
Structure of java Program
• Documentation (commenting).
• Packages.
• Import statements.
• Interfaces
• Class definitions
• Main method.
Simple java program
• /* multi line commenting */
• Package p;
• Import java.io.*;
• Class XYZ
• {
public static void main(String Args[])
{
int a=10,b=10;
• Int z=a+b;
System.out.println(“z: ”+z);
}
}
O/P
z:20
main method
• Why public
To access JVM by main
• Why static
– To access main method Without creating object of
main method contained class.
Variable

• Its value can be changed.


• It is have memory.
• Examples : name, roll_number , branch.
• Variable naming rules
– Starts with alphabet.
– Upper and lower case letters are different.
– We can use underscore to separate words.
– We can use $ symbol and name of variable should
not be keyword.
• /* calculating area of rectangle */
• Class Area
• {
int l,b;
Void get(int x,int y)
{
l=x,b=y;
}
Void put()
{
system.out.println(“area is”+(l*b));
}
}
• Class Rectangle
• {
public static void main(String arg[])
{
area a=new area();//object creation
a.get(10,20);//calling member function
a.put();
}
}
Output : area is 200.
Explanation of System.out.println
• Class System
• {
Static printstream out;
}
Println is method of out variable of type printStream
there in System class.
Data Types
• Every variable associate with one data type.
• What is the type of data and its size we can
know from data types.
• For integer
byte: -128 to 127
short: -32768 to 32767
int: -2,147,483,648 to 2,147,483,648
long: -9,223,372,036,854,775,808 to
9,223,372,036,854,775,807
• floating point:
float: size 4 bytes
double: size 8 bytes

Characters:

char: size 2 bytes(0 to 2^16 -1)

Boolean:
boolean (i.e., true/false).
Scope of variable
• Local variable scope:
– Variable declared inside the function or black are
called local variable.
Instance variable
data members of class other than static are called
Instance variable. Instance variable memory is
allocated when object is created.
• Class x
• {
int x;//instance variable
Void fun()
{
int p;//local variable
}
}
Default values of data types
• int- 0
• float -0.0f
• short 0
• long 0L
• byte 0
• double 0.0d
• boolean false
• char -null
• Reference -null
Type casting
• There is a situation where one data type
variable is stored into another type.
• In such situations we have to type cast it.
– Type variable1=(type)variable2;
Int m=90;
byte n=(byte)m;
long count = (byte)m;
No loss of information in following cases

• Byte- short long double float int


• short- int ,float , double, long
• char – int short long double
• int –float ,double, long
• float- double
• Byte b=50
• Float f=3,147f;
• Long l=123456789L;
• Short s=(short) b;->50
• Int l=(int) f;->3
• Float f1=(float) l;->1.23456789+e09
Condition operator
• Or terinary operator (exp1)?exp2:exp3;
• If exp1 is true exp2 is executed or exp3 is
executed.
• A=10;
• B=20;
• X=(A>B)?A:B;
• Ans X=?
Special Operator
• instanceOf operator
• It is to find object is belong to class or not.
• Syntax
– Classname instanceOf objectname;
For each loop
• Repeatedly execute group of elements in
collection;
• Syntax : for (variable:collection)
• int arr={10,20,30};
• for(int i:arr)
System.out.println(i);
Output: 10 20 30
Labeled continue and break
• Normal break is used to come out of inner
loop.
• Labeled break is used to come out of outer
loop.
• Normal continue is use to continue next
iteration of inner loop.
• Labeled continue is used to continue for next
iteration outer loop
Arrays
• It is group of elements of same type.
• When Array is created it will have fixed size.
• Creation of array
– Datatype arrayname[]={values};
Or Datatype arrayname[]=new datatype[];
Or Datatype arrayname[]=new datatype[]{values};
Multi dimensinal array
• It is array of arrays
• Int x[]=new int[4];
• X[0]=10;
• X[2]=20;
• System.out.println(x[0]+” ”+x[3]);
• o/p
?
• Once array is initilized after that you want to
change size of it previous data will be deleted.
Identify right declaration
• 1) int []a=new int[5];
• 2)int a[]=new int[5];
• 3)int a[5]=new int[5];
• 4)int a[]=new int[]{1,2,3};
• 5)int a[]=new int[3]{1,2,3};
Command line arguments
• There arguments are passed at run time to
arguments for main method.
• These arguments are String type.
String
• Group of charecters
• It is class
• Creation
String class methods
• String concate (String )
• Char charAt(int)
• String compareTo(String)
• String SubString(int)
String Buffer
• Immutable
• StringBuffer s=new stringBuffer(“data”)
• Some methods of StringBuffer
• setCharAt(char,index)
• setLenght(int)
Class and object
• Wrapping of data and function at one place.
• Object are created from class
• Defining class
• Class class_name
• {
– Variable
– methods
• }
• Object creation
Class-name object_name= new class-name();
Example:
class rectangle
{
int x,y;
void fun(int p,int q)
{
x=p;y=q;
}
}
Rectangle r;
r=new rectangle();
r.fun();
Reading data from keyboard
• java.util.*;
• Class read
• {
Public static void main(String ar[])
{ Scanner s=new Scanner(System.in);
System.out.println(“enter value”);
double d=s.nextDouble();
System.out.println(d);
}
constructor
• Special member function
• Its name is same as class and wont return any thing.
• Main purpose is to allocate memory for object
• Class class_name
• { class_name()//DEFAULT CONSTRUCTOR
{
}
class_name(argument list)//parameterised constructor
{
}
}
• Class area
• {
private int l;
private int b;
area()
{
l=10;b=20;
}
area(int l,int b)
{
this.l=l;this.b=b;
}
• Void areacal()
• {System.out.println(“area :”+(l*b));
• }
• }//closing area class
• Class rect
• {
Public static void main(String a[])
{
area a1=new area();
a1.areacal();//200
area a2=new area(10,30);
a2.areacal();//300
}
}
Here constructor overloading happens
STATIC VARIABLE
• Known as Class variable.
• Its value is shared by all the objects of its class
• We can access by class name.
• classname.staticVariablename;
• Only one copy created for class.
Static method
• Static method can be accessed by class name
not with object
• Static method can access only static variable.
• If you want to access non static variable inside
static method it will give compilation error.
• Static method can not reference this and
super any way.
• class staticexample
• {
• static int count=0;
• int x=0;
• void funct()
• {
• x++;count++;
• System.out.println("x count"+x+" "+count);
• }
• public static void main(String a11[])
• {
• aa a1=new aa();
• aa a2=new aa();
• a1.funct();
• a2.funct();
• }
• }
overloading
• In class two or more functions having the same name
but they differ in number of arguments or type of
arguments.
• Syntax:
• Class class_name{
• Return_Type same_funct_name(argument_list1)
•{
}
• Return_type same_funct_name(argument_list2)
•{
}
•}
overridding
• In the derived class and base classes in
inheritance having the same function
prototype declaration they may have different
definition .
• Both overriden function in base and derived
classes having the same name , argument list
and return type
• class A
• {
• void sum(int a,int b)
• {
• System.out.println("sum of two int numbers:"+(a+b));
• }
• void sum(float a,float b)
• {
• System.out.println("sum of two float numbers:"+(a+b));
• }
• void display()
• {
• sum(9,10);
• sum(9.00f,10.13f);
• }
• }
• class B extends A
• {
• void sub(int a,int b)
• {
• System.out.println("subtraction of two int numbers:"+(a-b));
• }
• void sub(float a,float b)
• {
• System.out.println("subtraction of two float numbers:"+(a-b));
• }
• void display()
• {
• sub(10,9);
• sub(10.13f,2.15f);
• }
• public static void main(String a[])
• {
• A A1=new A();
• B B1=new B();
• A1.display();
• B1.display();
• }
• }

• O/p::
This reference
• It is used to reference current object.
• this.variablename;
Difference between == and equals()

• == checks for references


• Equals() checks actual content.
• String s1=new String ("manash");
• String s2=new String ("manash");
• System.out.println("=="+(s1==s2));
• System.out.println("equals "+s1.equals(s2));
• o/p:?
Overloading main method
• Public static void main(String arg[])

• Public static void main(int arg[])


Access specifies
• Restricting data and functions from outside of class
through access specifies.
– Public , private , protected,default.
Public – universal accessibility . sub classes and non sub
classes of same package as well as sub classes and non
sub classes of other package.
Private- accessible in same class only.
Protected: sub classes and non sub classes of same
package. Sub classes of other package.
Default: sub classes and non sub classes of same package.
• Syntax:
• Accessspecifier data type variablename;
• Example
• Protected int x;
• Public void funt(){
}
• class xyz
• {
• private int x=20;
• public int y=23;
• public void funct()
• {
• System.out.println(x+" "+y);
• }
• }
• class abc
• {
• public static void main(String a[])
• {
• xyz x1=new xyz();
• System.out.println(" public"+x1.y+" ");
• System.out.println(" private"+x1.x+" ");// private data aceessing error
• x1.funct();
• }

• }
• o/p: compilation error
Wrapper classes
• By using wrapper classes we convert primitive
type to object type.
• By using wrapper classes we convert primitive
type like int,float, char,float,long,char to
object type.
• Wrapper classes are there in java.lang
package.
• Simple class • Wrapper class
boolean Boolean
char Character.
double Double
float Float
int Integer
long Long
Converting primitive to object type
• Integer IntObject=new integer(int)
• Like Float ,Double, Long.
Converting object number to primitive type

• By using xValue()method
• In place of x int,float,long,double.
• Example
• int i= IntValuedObject.floatValue();
Converting numerical string to primitive
string
• int i=Integer.parseInt(str);
• long l=Long.parseLong(Srt);
• Like wise for double float
Converting String object to numeric object

• Xvalue=x.valueOf(Str);
• In place of x we have use
Double,Float,Integer,Long
Converting number to string Object
• Str=X.toString(i);
• X->Integer,Float,Double,Long
• i->int,float,double,long
• Example
• String s=Integer.toString(i);
final variable, method, class
• final variable
• When we declare variable as final its value can not
be change. If you do so it will give compilation error.
• Syntax : final datatype variable=value;
• Example:final int x=30;
• final int p=45;
• Void funct(){
p=5;// it will give compilation error
}
• Final method can not be overridden.
• Final classes can not be inherited.
• Can we execute the class without main method
• Ans) yes by using static block we can execute the
java program
• Classs x{
Static void f()
{ System.out.println(static funct);
}
static{
f();
}
}o/p???
Finalize method
• Non object resources can removed from
memory manually by finalize() method.
• Garbage collector is automatically called by
jvm to free the object used in program after
completion execution.
Abstract method & class
• Abstract method wont have definition or body.
• It is opposite to final method.
• It must be overridden .
• If class contain one or more abstract method
then we must give the name of class as
abstract.
• Syntax:
• abstract class shape// abstract class
• {
abstract void draw(); //abstract method
• }
• We cant create object for abstract class
• We must inherit the abstract class to write
definition for abstract method.
Inheritance

• Reusability property we can achieved by


inheritance property.
• Already existed class is called as parent class .
• Parent or base class properties are inherited
new class called child class or derived class.
• Synatx:
• Class derived_class extends base_class
{
}
Example :
class x
{
protected int x=20;
void put()
{ System.out.println(x); }
}
class Derived1 extends x
{
int y=30;
void putDerived()
{ System.out.println(y); }
public static void main(String arg[])
{
Derived1 d=new Derived1 ();
d.put();
d.putDerived();
}
}
O/p????
Same program with constructor and super

• class x
• {
• protected int x;
• x(int x ){this.x=x;
• }
• void put()
• { System.out.println(x); }
• }
• class Derived1 extends x
• {
• int y;
• Derived1(int x,int y)
• {
• super(x);
• this.y=y;
• }
• void putDerived()
• { System.out.println(y); }
• public static void main(String arg[])
• {
• Derived1 d=new Derived1 (20,30);
• d.put();
• d.putDerived();
• }
• }
• o/p???
interface
• It is group of related methods with empty
bodies.
• Java does not support multiple inheritance
that is implemented with interface.
• Class can not extend more than one class.
• Example : class A extends B,C{ }// error
• Here B,C classes.
Defining interface
• Interface contain only abstract methods and final
fields.
• By default all methods public static final
• By default all variable in interface are public abstract.
• Syntax:
interface Interface_name{
final Varibles ;
abstract Methods;
}
• Example:
• Interface xyz
{
int i=0;
Void funct();
}
When ever we extend an interface output is interface.
When ever we implement interface output is class.
We can extend more than one interface but not class.
• interface x{}
• interface y{}
• interface z extends x,y{}
Implementing interface
When we write interface we must and should write implementation of
interface.
Syntax :
Class class_name implements inteface_name
{

}
More general form
Class class_name extends superclass implements
inteface_name1,interface_name2
{

}
• interface B
• {
• public int b=20;
• public void f2();

• }

• class C implements B
• {
• public void f1()
• {
• System.out.println(a);
• }
• public void f2()
• {
• System.out.println(b);
• }

• }

• class Interface
• {
• public static void main(String args[])
• {
• C c1=new C();
• c1.f1();
• c1.f2();

• }
• }
Difference between abstract class and
interface
Abstract class interface
• It can have non final and non • It can have static final
static variable. variable.
• it can have abstract methods • It having only abstract
as well as concrete methods. methods.
• We can use all access specifies.
• We have to use only public
• Abstract class uses extends access specifies.
keyword to extend abstract
• Interface is implemented to
class
another class.
• It can have constructor
• It cannot have constructors.
Interface to abstract class
• Interface b
• {
void func();
• }
• Abstract class aa implements b
• {
//no def for funct
• }
Multi threading
• Multi tasking :executing several programs
simultaniously. It is a OS level concept.

• Multi threading is conceptual programming


paradigm, where program is divided into sub
parts called as threads and these threads run
concurrently. It is programmer level concept.
Creation of thread
1) By creating thread class.
Define a class that extends thread class
override run method()

2)By converting class to thread


define a class that implements runnable
interface and write definition for run() method
Creating thread class
• class A extends Thread
• {
• public void run()
• {
• try
• { for(int i=0;i<15;i++)
• {
• System.out.println(" Ai :"+i);
• }
• System.out.println("End of thread A");
• }
• catch(Exception E)
• {

• }
• }

• }
• class B extends Thread
• {

• public void run()


• { try
• {
• for(int i=0;i<15;i++)
• { System.out.println("Bi :"+i);
• }
• System.out.println("End of thread B");
• }
• catch(Exception E){}
• }
• }
• class C
• {
• public static void main(String a[])
• {
• A A1=new A();
• A1.start();
• B B1=new B();
• B1.start();
• }

• }
Syncronized
• Multiple threads try to access shared resource
at that time we may get strange results.
• At that time we can apply lock by using
Syncronized lock to either block or method,
• Syntax :
syncronized return_type method(){ }
syncronized(lock_object){ }
Exception handling
An exception cased due to runtime errors in
programs . Due to the errors we will come out
of program leads to serious problems.
We handle this serious error by using exception
handling mechanism.
Exception handling mechanism
• Find error(exception)
• Inform that an error has been occurred(throw)
• Receive the error information(catch)
• Take corrective action(handle the exception)
Example program
• class DevideByZero
• {
• public static void main(String a[])
• {
• int a1=Integer.parseInt(a[0]);
• int a2=Integer.parseInt(a[1]);
• try
• {
• System.out.println("a1/a2"+(a1/a2));
• }
• catch(ArrayIndexOutOfBoundsException e)
• {
• System.out.println(e);
• }
• catch(ArithmeticException e)
• {
• System.out.println(e);
• }


• finally
• {
• System.out.println("finnally compulsary exiquited");
}
• }
Package
• It is Grouping of related classes and interfaces
together.
• Benefits:
– Reusability
– Easy to locate a file.
– Problem solved related to same naming of classes.
Types of packages
1) user defined package
We can create our own packages called as user defined packages.
2)Build in package
already exist in java api like
java.lang.*;
java.util.*;
java.math.*;
java.io.*;
java.net.*;
java.aplet.*;
User defined package
• Double y=java.lang.math.sqrt(2);
• Sqrt() is method to calculate square root . This
method is there in math class. Math class is
there in lang package.
• Java.io.*;
• * means io package contained all classes will
come to our program.
Creating package
• While creating package we have to use the package
keyword .
• Package is directory of classes .
• Syntax for creating package
Package package_name;
Class class_in_package
{
//body of class
}
• Example of package:
• Package first_package;
• Public class first_class
• {
public void f()
{
System.out.println(“using package”);
}
• }
• Compiling package
– Syntax: javac –d directoryname filename.java
Using of package in another program
• Import keyword is used to use the package in another program
• Import first_package.*;// package content will //come to
your program.
• Class b
• {
• Public static void main(String arg[])
•{
first_package.first_class x1=new first_package.first_class ();
X1.f();
•}
• }
• O/p:??
Predefined package
OR Build in package
already exist in java api like
java.lang.*;
java.util.*;
java.math.*;
java.io.*;
java.net.*;
java.aplet.*;
Java.lang.*
• This package automatically imported to java
program.
• It contains classes like
– Object
– Math
– The wrapper classes
– String
– StringBuffer
Java.util.*;
• It provides utility classes like vector , stack,
hast table, random numbers.
• Main classes are
– Scanner
– Stack
– Vector
– Date
• Java.io.*;
– They provide facility for input and output of data.

Java.awt.*;
-It provides class for preparing graphical user
interface.
Java.applet.*;
-it provides classes for creating and implementing of
classes.
applet
• It is a small java program used to create dynamic web
applications.
• To run applet web browser or appletviewer is
needed.classes needed to create applet are Graphics
class and applet class.
• By using applet we can add images , audio , video to web
application. We can perform arithmetic operations.
• Application:
interactive games.
we can add multi media to applications.
• Which four options describe the correct default
values for array elements of the types indicated?
1 int -> 0
2 String -> "null"
3 Dog -> null
4char -> '\u0000'
5float -> 0.0f
6boolean -> true
A.1, 2, 3, 4 B.1, 3, 4, 5 C.2, 4, 5, 6 D.3, 4, 5, 6
• Which one of these lists contains only Java
programming language keywords?
• A.class, if, void, long, Int, continue
• B.goto, instanceof, native, finally, default,
throws
• C.try, virtual, throw, final, volatile, transient
• D.strictfp, constant, super, implements, do
• E.byte, break, assert, switch, include
• Which will legally declare, construct, and
initialize an array?
A.int [] myList = {"1", "2", "3"};
B.int [] myList = (5, 8, 2);
C.int myList [] [] = {4,9,7,0};
D.int myList [] = {4, 3, 7};
Which is a reserved word in the Java
programming language?
A.methodB.nativeC.subclassesD.referenceE.arra
y
• Which is a valid keyword in java?
A.interfaceB.stringC.FloatD.unsigned
• public interface Foo { int k = 4; /* Line 3 */ } Which
three piece of codes are equivalent to line 3?
• 1final int k = 4;
• 2public int k = 4;
• 3static int k = 4;
• 4abstract int k = 4;
• 5volatile int k = 4;
• 6protected int k = 4;
• A.1, 2 and 3B.2, 3 and 4C.3, 4 and 5D.4, 5 and 6
• Following code
• int NUM=9.6 will it execute properly.

• ??
• class bits
• {
• public static void main(String arg[])
• {
• int i=10;
• double d=(float)i;
• System.out.println(i);
• }
• }
• Will it execute or not???
Java runs on
• Windows
• unix
• Mac
• all
IsEmpty is it a valid source file name?
• Yes
• no
• Size of char
16 bits
8bits
32bits
none
• What is the default value for local variable
• 0
• 1
• null
• No default value..
Which is valid declaration of a float?
A.float f = 1F;
B.float f = 1.0;
C.float f = "1";
D.float f = 1.0d;
public class foo { public static void
main(String[]args)throws Exception
{ java.io.PrintWriter out = new
java.io.PrintWriter(); new
java.io.OutputStreamWriter(System.out,true);
out.println("Hello"); } }
What line of code should replace the missing
statement to make this program compile?
• A.No statement required.
• B.import java.io.*;
• C.include java.io.*;
• D.import java.io.PrintWriter;
What is the numerical range of char?
• A.0 to 32767
• B.0 to 65535
• C.-256 to 255
• D.-32768 to 32767
Which of the following are Java reserved words?
1run
2import
3default
4implement
• A.1 and 2
• B.2 and 3
• C.3 and 4
• D.2 and 4
What will be the output of the program?
public class Test { public static void main (String[]
args) { String foo = args[1]; String bar = args[2];
String baz = args[3]; System.out.println("baz = " +
baz); /* Line 8 */ } } And the command line
invocation:
> java Test red green blue
A.baz = B.baz = null C.baz = blue D.Runtime
Exception
• public class Test { public static void main
(String args[]) { String str = NULL;
System.out.println(str); } }
O/P
A NULL B.Compile Error C.Code runs but no
output D.Runtime Exception
• public class Test { private static int[] x; public
static void main(String[] args)
{ System.out.println(x[0]); } }
• A 0  B.null C.Compile Error
D.NullPointerException at runtime
• public class Test { private static float[] f = new
float[2]; public static void main (String[] args) {
System.out.println("f[0] = " + f[0]); } }
A.f[0] = 0 B.f[0] = 0.0 C.Compile Error
D.Runtime Exception
• public void test(int x)
• { int odd = 1; if(odd)
{ System.out.println("odd"); } else
{ System.out.println("even"); } } Which
statement is true?
• A.Compilation fails.B."odd" will always be
output.C."even" will always be output.D."odd"
will be output for odd values of x, and "even"
for even values.
• while ( 1 ) { System.out.print("x plus one is " +
(x + 1));}
• Will this statement execute
• Class xyz
• {
int I;
Public static void main(String a[])
{
System.out.println(“l:”+this.l);
}
}
What is output?
• What is the out of program?
• Class xyz{
int x;
Xyz(int x)
{this.x=x;System.out.println(“x vlue is:”+x);}
public static void main(String arg[])
{xyz x1=new xyz();
}
}
Accessing super class member from sub
class.
• A sub class include all of members of its super
class.
• But, it cannot directly access those members
of super class that have declared as private.
• Class AAA{
• private int x=10;
• public void func(){
System.out.println(x);}}
Class bbb extends AAA{
void funct1() {System.out.println(x);}
Psvm(String a[]){ bbb b=new bbb();
b.funct1();
}
What is the output????
Super keyword
• Two use
– First is to call super class constructor from sub
class constructor.
– Second usage is to access a member of super class
that has been overridden by a sub class.
– Syntax:
– Super(parameter-list)
Using super to call super class constructors

• Super() if present, must always be the first


statement executed inside a subclass
constructor.
• It clearly tells you the order of constructors in
class hierarchy.
• Constructors are invoked in order of their
derivation.
Constructor invocation order
• Class x{
x(){ SOP(“inside X constructor”);}}
Class y extends x{
y(){SOP(“inside y constructor”);}}
Class z extends y{
z(){SOP(“inside z constructor”);}}
Class orderOfConstructorcalling{psvm(String a[])
{ z z1=new z1();}
}
O/p??
What is the o/p
• Class x{
x(){ SOP(“inside X constructor”);}
x(int i){ SOP(“inside X parameterised constructor”);}

}
Class y extends x{
y(){SOP(“inside y constructor”);}
y(int i){ super(i);SOP(“inside y parameterised
constructor”);}

}
Class z extends y{
z(){SOP(“inside z constructor”);}
z(int i){ super(i);SOP(“inside z parameterised
constructor”);}
}
Class orderOfConstructorcalling{psvm(String a[])
{ z z1=new z1();}
}
• o/p??
What is the o/p
• Class x{
x(){ SOP(“inside X constructor”);}
x(int i){ SOP(“inside X parameterised constructor”);}

}
Class y extends x{
y(){SOP(“inside y constructor”);}
y(int i){ super(i);SOP(“inside y parameterised constructor”);}

}
Class z extends y{
z(){SOP(“inside z constructor”);}
z(int i){ super(i);SOP(“inside z parameterised
constructor”);}
}
Class orderOfConstructorcalling{psvm(String a[])
{ z z1=new z1(100);}
}
• o/p??
Super to call overridden method
• Class AAA
• { int x,y;
AAA(int m,int n){x=m;y=n;}
Void display(){SOP(x+” ”+y);}
}
Class BBB{
int z;
BBB(int p,int q,int r){super(p,q);z=r; }
Void display(){SOP(z);}}
• Class ccc{
• Psvm(String a[])
• {BBB b1=new BBB(1,2,3);
• B1.display();
• }}
• o/p??
What is the out put
• class xxx{
• void fun(){SOP(“parent void type”);}
• }

• class bits2 extends xxx


• { int fun(){SOP(“child void type”);}
• public static void main(String arg[])
• {
• bits2 b1=new bits2();

• }
• }
The cosmic class –Object class
• Java defines a special class called Object . It is
available in java.lang package.
• All other classes are sub classes of Object.
• Object is superclass of all other classes . i.e
java’s own classes, as well as user defined
classes.
Point out error in program
• final class xxx
• {
• int x=9;
• final void m1()
• {
• System.out.println(x);
• }
• }
• class yyy extends xxx
• {
• int y=7;
• void m1(){
• super.m1();
• System.out.println(y);}
• public static void main(String ar[]){
• yyy y1=new yyy();
• y1.m1();
• }
• }
Abstract and final
• abstract class xxx
• {
• int x=9;
• abstract final void m1()
• {
• System.out.println(x);
• }
• }
• class yyy extends xxx
• {
• int y=7;
• void m2(){
• super.m1();
• System.out.println(y);}
• public static void main(String ar[]){
• yyy y1=new yyy();
• y1.m1(); y1.m2();
• }
• }
• Find error???
• Which one is not inbuild java package?
• A java.io
• B java.sql
• C java.dbms
• D java.net
• Which one is correct usage of import
statement?
• A import java.*;
• B import java.lang.*;
• C import *;
• D import *.*;
Will this code compile
• interface t1
• {
• private int a=10;
• protected void fun();

• }
• class bits4 implements t1
• {
• public void fun(){
• System.out.println();
• }
• }
Will this program compile
• interface t1
• {
• static int a=10;
• static void fun();

• }
• class bits5 implements t1
• {
• public void fun(){
• System.out.println();
• }
• }
Will the following code compile successfully?

• interface t1
• {
• int a=10;
• void fun();

• }
• class bits6 extends t1
• {
• public void fun(){
• System.out.println();
• }
• }
Will the following code compile?
• interface t1
• {
• int a=10;
• void fun();

• }
• interface bits7 implements t1
• {
• public void fun2();
• }
• An interface can not implement or extends a
class or interface.
Will this program comple?
• class xxx
• {
• public static void main(String s[])
• {
• for (int i=0;i<args.length;i++)
• System.out.println(args[i]);
• }
• }
Will this program compile
• class bits9
• {
• public static void main(String a[])
• {
• try{

• int i=Integer.parseInt(a[0]);
• System.out.println("i:"+i);
• }
• System.out.println("CSE");
• catch(Exception e){
• System.out.println("exception is caught");
• }
• }
• }
Multiple catch statements in exception
handling
• When you use multiple catch statements , it is
important to remember that exception
subclass must come before any of their
exception super classes.
• class bits10
• {
• public static void main(String a[])
• {
• try{

• int i=Integer.parseInt(a[0]);
• System.out.println("i:"+i);
• }
• catch(Exception e){
• System.out.println("exception is caught");}
• catch(RuntimeException e)
• {
• System.out.println("exception
is caught");
• }
• }

• }
• Exception
– RuntimeException
– IOexception
– SQLException
– InterruptedException
• All RunTimeExceptions are checked exception.
Remaining all are unchecked exceptions

• RuntimeException
– ArithmeticException
– NumberFormateException
– NullPointerException
– IndexOutOfBoundsException
collection
• A collection — sometimes called a container
— is simply an object that groups multiple
elements into a single unit. Collections are
used to store, retrieve, manipulate, and
communicate aggregate data. 
Structure of collection
Thread priority
• All java threads have a priority in range of 1-
10.
• Top priority is 10, lowest priority is 1.
• Normal priority by default is 5.
• StringBuffer • StringBuilder
• StringBuffer • StringBuilder is non-
is synchronized i.e. thread synchronized i.e. not
safe. It means two thread safe. It means
threads can't call the two threads can call the
methods of StringBuffer methods of StringBuilder
simultaneously. simultaneously.
• StringBuffer is less • StringBuilder is more
efficient than efficient than
StringBuilder. StringBuffer.
Frequently asked java questions In interview.

• What Is difference between c++ and Java?


• Why java is platform independent ?
• Why java is platform independent code? how?
• What is JVM?
• What is java byte code?
• What is difference between abstract class and
interface?
• What is the perpose of garbage collectio in java?
• What is the benefits of finalize() method in java?
• What are different types of collections available
in java?
• Why String are immutable?advatage?
• Is java is passby value or pass by referenced?
• Explain Static keyword?diffence between
instance variable and class (static) variable
• Explain exception in java?
• What is the difference between final and
finally?
• What is transient keyword in java?
• Explain polymorphism, encapsulation and
inheritance?
• What is the difference between stringBuffer
and stringBuilder?
• Explain class loading in java?
• Difference between final,finally,finalize() ?
• Difference between String and StringBuffer?
• Difference between == and equals()method
• Difference between interface abstract class
and concrete class?
• Explain system.out.println()
• Explain public static void main(String a[]){}?
• Difference between overloading and
overriding ?
What is Transient?

• The keyword transient in Java used to indicate that


the variable should not be serialized. By default all
the variables in the object is converted to persistent
state. In some cases, you may want to avoid
persisting some variables because you don’t have
the necessity to transfer across the network. So,
you can declare those variables as transient. If the
variable is declared as transient, then it will not be
persisted. It is the main purpose of the transient
keyword.

S-ar putea să vă placă și