JAVA Complete Part I
JAVA Complete Part I
Java is an Object-Oriented programming language The primary objective of Java programming language
developed by James Gosling in 1991. The team creation was to make it portable, simple and secure
initiated this project to develop a language for digital programming language. Apart from this, there are also
devices such as set-top boxes, television, etc. some excellent features which play an important role
Originally C++ was considered to be used in the project in the popularity of this language. The features of
but the idea was rejected for several reasons e.g. Java are also known as java buzzwords.
Platform dependency, more memorey requirement etc.
Gosling endeavored to alter and expand C++ however A list of most important features of Java language is
before long surrendered that for making another stage given below.
called Green. James Gosling and his team called their
project “Greentalk” and its file extension was .gt and 1. Simple
later became to known as “OAK”.
2. Object-Oriented
Why “Oak”?
3. Portable
The name Oak was used by Gosling after an oak
tree that remained outside his office. Also, Oak is an 4. Platform independent
image of solidarity and picked as a national tree of
numerous nations like the U.S.A., France, Germany, 5. Secured
Romania, etc. But they had to later rename it as “JAVA”
as it was already a trademark by Oak Technologies. 6. Robust
H.O. : B-5,Dev nagar ,opp. Kamal & company ,gopalpura ,Jaipur Tel : 0141-2708941 , Mob : 9887755436, 9413223636 Visit us at : www.fluxeducare.in
CORE JAVA PROGRAMMING
• No explicit pointer
• Java Programs run inside a virtual machine
sandbox High-performance
• Classloader: Classloader in Java is a part of the
Java is faster than other traditional interpreted
Java Runtime Environment (JRE) which is used
programming languages because Java bytecode is
to load Java classes into the Java Virtual
"close" to native code. It is still a little bit slower than
Machine dynamically. It adds security by
a compiled language (e.g., C++). Java is an interpreted
separating the package for the classes of the
language that is why it is slower than compiled
local file system from those that are imported
languages, e.g., C, C++, etc.
from network sources.
• Bytecode Verifier: It checks the code fragments
for illegal code that can violate access right to
objects. Distributed
• Security Manager: It determines what resources
a class can access such as reading and writing Java is distributed because it facilitates users to
to the local disk. create distributed applications in Java. RMI and EJB
are used for creating distributed applications. This
Java language provides these securities by default. feature of Java makes us able to access files by calling
Some security can also be provided by an application the methods from any machine on the internet.
developer explicitly through SSL, JAAS, Cryptography,
etc.
Multi-threaded
H.O. : B-5,Dev nagar ,opp. Kamal & company ,gopalpura ,Jaipur Tel : 0141-2708941 , Mob : 9887755436, 9413223636 Visit us at : www.fluxeducare.in
CORE JAVA PROGRAMMING
OBJECT-ORIENTED 3. Abstraction
Java is an object-oriented programming language. Abstraction is a process where you show only
Everything in Java is an object. Object-oriented means “relevant” data and “hide” unnecessary details of an
we organize our software as a combination of different object from the user. For example, when you login to
types of objects that incorporates both data and your bank account online, you enter your user_id and
behavior. password and press login, what happens when you
press login, how the input data sent to server, how it
The first object oriented programming language is gets verified is all abstracted away from the you.
SIMULA and first pure object oriented programming
language is SMALLTALK. Data Abstraction may also be defined as the process
of identifying only the required characteristics of an
Object-oriented programming (OOPs) is a methodology object ignoring the irrelevant details. The properties
that simplifies software development and maintenance and behaviors of an object differentiate it from other
by providing some rules. Basic concepts of OOPs are: objects of similar type and also help in
classifying/grouping the objects.
1. Object
In java, abstraction is achieved by interfaces and
2. Class
abstract classes.
3. Abstraction
4. Encapsulation
4. Encapsulation
Encapsulation is binding the data with the code that
5. Polymorphism manipulates it. It keeps the data and the code safe
from external interference. Class itself is the example
6. Inheritance of encapsulation.
2. Class
H.O. : B-5,Dev nagar ,opp. Kamal & company ,gopalpura ,Jaipur Tel : 0141-2708941 , Mob : 9887755436, 9413223636 Visit us at : www.fluxeducare.in
CORE JAVA PROGRAMMING
protected: The scope of a protected variable is within • Number of parameters passed to a method
the class which declares it and, in the class, which • Datatype of parameters
inherits from the class (Scope is class and subclass). • Sequence of datatypes when passed to a
method.
Default: Scope is Package Level. We do not need to
explicitly mention default as when we do not mention 6. Inheritance
any access specifier it is considered as default.
The process by which one class acquires the
5. Polymorphism properties and functionalities of another class is
called inheritance. Inheritance provides the idea of
Polymorphism is an object oriented programming reusability of code and each sub class defines only
feature that allows us to perform a single action in those features that are unique to it, rest of the
different ways. Polymorphism means taking many features can be inherited from the parent class.
forms, where ‘poly’ means many and ‘morph’ means
forms. It is the ability of a variable, function or object to • Inheritance is a process of defining a new class
take on multiple forms. In other words, polymorphism based on an existing class by extending its common
allows you define one interface or method and have data members and methods.
multiple implementations.
• Inheritance allows us to reuse of code, it
improves reusability in your java application.
Types of Inheritance
In Java, runtime polymorphism refers to a process in Multiple Inheritance: It refers to the concept of one
which a call to an overridden method is resolved at class extending more than one classes, which means a
runtime rather than at compile-time. In this, a child class has two parent classes. Java doesn’t
reference variable is used to call an overridden method support multiple inheritance directly we can
of a superclass at run time. Method overriding is an implement it indirectly using concept of interface.
example of run time polymorphism.
H.O. : B-5,Dev nagar ,opp. Kamal & company ,gopalpura ,Jaipur Tel : 0141-2708941 , Mob : 9887755436, 9413223636 Visit us at : www.fluxeducare.in
CORE JAVA PROGRAMMING
C++ vs Java
There are many differences and similarities between the C++ programming language and Java. A list of top
differences between C++ and Java are given below:
Use C++ is mainly used for system Java is mainly used for application
programming. programming. It is widely used in window,
web-based, enterprise and mobile applications.
Goto C++ supports the goto statement. Java doesn't support the goto statement.
Multiple C++ supports multiple inheritance. Java doesn't support multiple inheritance
inheritance through class. It can be achieved by interfaces
in java.
Operator C++ supports operator overloading. Java doesn't support operator overloading.
Overloading
Pointers C++ supports pointers. You can Java supports pointer internally. However, you
write pointer program in C++. can't write the pointer program in java. It
means java has restricted pointer support in
java.
Compiler and C++ uses compiler only. C++ is Java uses compiler and interpreter both. Java
Interpreter compiled and run using the source code is converted into bytecode at
compiler which converts source compilation time. The interpreter executes this
code into machine code so, C++ is bytecode at runtime and produces output. Java
platform dependent. is interpreted that is why it is platform
independent.
Call by Value and C++ supports both call by value and Java supports call by value only. There is no
Call by reference call by reference. call by reference in java.
Structure and C++ supports structures and Java doesn't support structures and unions.
Union unions.
Thread Support C++ doesn't have built-in support Java has built-in thread support.
for threads. It relies on third-party
libraries for thread support.
Documentation C++ doesn't support documentation Java supports documentation comment (/** ...
comment comment. */) to create documentation for java source
code.
H.O. : B-5,Dev nagar ,opp. Kamal & company ,gopalpura ,Jaipur Tel : 0141-2708941 , Mob : 9887755436, 9413223636 Visit us at : www.fluxeducare.in
CORE JAVA PROGRAMMING
unsigned right C++ doesn't support >>> operator. Java supports unsigned right shift >>>
shift >>> operator that fills zero at the top for the
negative numbers. For positive numbers, it
works same like >> operator.
H.O. : B-5,Dev nagar ,opp. Kamal & company ,gopalpura ,Jaipur Tel : 0141-2708941 , Mob : 9887755436, 9413223636 Visit us at : www.fluxeducare.in
CORE JAVA PROGRAMMING
3. Literals
4. Operators 1. byte
Every name in java is called identifier such as class • The most significant bit is called “Sign Bit” . 0
name, method name, variable name etc. means positive value, 1 means negative value.
e.g.
Data type
Short s = 32767
Every variable has a type, every expression has a type
Short s = -32768
and all types are strictly define more over every
assignment should be checked by the compiler by the Short s = 32768 (compile time error)
type compatibility hence java language is considered as
strongly typed programming language. Short s = 123.456 (compile time error)
1. Numeric data types (For represent numbers) • Short datatype is most suitable if we are using 16-
bit processors like 8086 but these processors are
a) Integral data types completely outdated.
1) Byte
2) Short
H.O. : B-5,Dev nagar ,opp. Kamal & company ,gopalpura ,Jaipur Tel : 0141-2708941 , Mob : 9887755436, 9413223636 Visit us at : www.fluxeducare.in
CORE JAVA PROGRAMMING
Range= -231 to 231-1 [-2147483648 to 2147488647] Range:- Not Applicable [but allowed values are
true/false]
• In C language the size of int is varied from platform
to platform. For 16-bit processor it is 2 bytes and
for 32-bit processor it is 4 bytes.
Char Data Type
• The main advantage of this approach is read and
writes operations we can perform very efficiently Size: 2-bytes
and performance will be improved, but the main
Range: 0 to 65535
disadvantage of this approach is the chance of
failing c program is very high if we are changing
• In languages like C and C++ we can use only ASCII
platform. C language is not considered robust.
characters and to represent all ASCII characters 8-
bytes are enough. Hence char size is 1-byte.
• But in java the size of int is 4 bytes irrespective of
its platform. The advantage of this approach is the
• But in java we can use Unicode Characters which
chance of failing java program is very less. If we
covers worldwide all alphabets sets. The no. of
change the platform java is considered robust.
Unicode characters is “ >256” and hence 1-byte is
not enough to represent all characters compulsory
• But the main disadvantage in this approach is read
we should go for 2-bytes.
and write operation will become costly and
performance will be reduced.
4. long
Literals
Whenever int is not enough to hold big values then we
A constant value which can be assign to the variable is
should go for long data type.
called a ‘literal’.
Size = 8 bytes
1. Size: 4 bytes 1. Size: 8 bytes For the integral datatype (byte, short, int, long) the
following are various ways to specify literal values :
2. Range: -3.4e38to 2. Range: -1.7e308 to
3.4e38 1.7e308 1. Decimal literals
3. Hexadecimal Literals
• For the extra digits we can use both upper case and
lower case.
H.O. : B-5,Dev nagar ,opp. Kamal & company ,gopalpura ,Jaipur Tel : 0141-2708941 , Mob : 9887755436, 9413223636 Visit us at : www.fluxeducare.in
CORE JAVA PROGRAMMING
• This is one of the very few places where Java is not e.g. double d= 128.4567D;
case sensitive.
float f= 123.4567d; (compile time error)
• Literals value should be prefixed with 0x or 0X
We can specify floating point literal only in decimal form
e.g. int x=0x10 or int x= 0X10 and we can’t specify in octal and hexadecimal form.
double d=123.456;(valid)
6. int x=0xabb2cd; //(valid) • we can't assign floating point literal directly to the
integral types
• If we are assigning integral literal to the byte 3. boolean b=True;//C.E:cannot find symbol(invalid)
variable and that integral literal is within the range
of byte then it treats as byte literal automatically, 4. boolean b="true";//C.E:incompatible types(invalid)
similarly short literal also
Char Literals
byte b=10;
• A Char literal can be represented as single
byte b=130; (compile time error) character with in single codes.
Every floating point literal is by default double type and char ch= ‘ab’ (compile time error)
hence we can’t assign directly to float variable. We can
specify explicitly floating point literal is the float type by • A char literal can be represented as integral literal
suffixing with ‘f’ or ‘F’. which represents Unicode of that character.
e.g. float f=123.456f; We can specify integral literal either in decimal form or
octal form or hexadecimal form. But allowed range 0 to
double d=123.456; 65535.
H.O. : B-5,Dev nagar ,opp. Kamal & company ,gopalpura ,Jaipur Tel : 0141-2708941 , Mob : 9887755436, 9413223636 Visit us at : www.fluxeducare.in
CORE JAVA PROGRAMMING
s.o.p(ch); a
s.o.p(ch);
\n New line
\t Horizontal tab
\r Carriage return
\b Back space
\f Form feed
\’ Single quads
\” Double quads
\\ Back slach
String Literals
H.O. : B-5,Dev nagar ,opp. Kamal & company ,gopalpura ,Jaipur Tel : 0141-2708941 , Mob : 9887755436, 9413223636 Visit us at : www.fluxeducare.in
CORE JAVA PROGRAMMING
Keywords
In java there are 53 reserved words which is divided into two categories
1. Reserved keywords
2. Reserved literals
There are 50 reserved keywords and 3 reserved literals which can be divided as follows
Data Control Modifiers Excep Class Object Ret Othe unuse liletr
type stateme tion related related urn r d al
nt handli typ
ng e
char do synchronized
break strictfp
continue transient
return volatile
H.O. : B-5,Dev nagar ,opp. Kamal & company ,gopalpura ,Jaipur Tel : 0141-2708941 , Mob : 9887755436, 9413223636 Visit us at : www.fluxeducare.in
CORE JAVA PROGRAMMING
The arguments which are passing from Command Within the main(), commandline arguments are
prompt are called Command Line arguments. available in string form.
}
Example 1
}
Class Test
Java Test “Note Book”
{
p.s.v.m(string[] args)
s.o.p(args[i]);
H.O. : B-5,Dev nagar ,opp. Kamal & company ,gopalpura ,Jaipur Tel : 0141-2708941 , Mob : 9887755436, 9413223636 Visit us at : www.fluxeducare.in
CORE JAVA PROGRAMMING
OPERATORS 5%-12=5
• Relational operator
2. Assignment operator
• Equality operator
If we want to assign something then we can use
• Bitwise operator assignment operator. It has following types
• [] operator += -+ %= *= /=
+,-,*,/,%
5%12=5
-5%12=-5
H.O. : B-5,Dev nagar ,opp. Kamal & company ,gopalpura ,Jaipur Tel : 0141-2708941 , Mob : 9887755436, 9413223636 Visit us at : www.fluxeducare.in
CORE JAVA PROGRAMMING
Unary operator is divided into two types The only overloaded operator in java is ‘+’ operator.
Sometimes it acts as arithmetic addition operator and
(i) prefix: ++x, --x sometime acts as string arithmetic operator or string
concatenation operator.
(ii) postfix: x++, x--
Example
Unary operator means
int a=10, b=20, c=30 ;
++x or x++ -->x=x+1
String d= “flux”;
--x or x-- -->x=x-1
s.o.p (a+b+c+d); 60flux
If we can use unary operator with assignment operator
then: s.o.p (a+b+d+c); 30flux30
y=++x x=11 y=11 (first increment and then assign) s.o.p (a+d+b+c); 10flux2030
Example: int x=4; We can apply relational operators for every primitive
data type except Boolean.
Int y= ++(++x); (compile time error)
Example 1. 10 > 20 false
We can’t apply increment & decrement operators for
the final variables. 2. ‘a’ < ‘b’ true
Ex- final int x= 4; x++; (compile time error) 3. 10 >= 10.0 true
We can apply increment & decrement operators for 4. ‘a’ < 125 true
every primitive data type except Boolean.
5. true <= true (compile time error)
Example
boolean b = true;
We can’t apply relational operator for the object types.
++b; (compile time error)
Example “flux” < “flux123” (compile time error)
In the case of increment & decrement operators the
required type casting, automatically performed by Nesting of relation operators we are not allowed to
the compiler. apply.
byte b++ is equivalent to b= (byte) (b+1); Example: Sop (10 < 20 <30) (compile time error)
H.O. : B-5,Dev nagar ,opp. Kamal & company ,gopalpura ,Jaipur Tel : 0141-2708941 , Mob : 9887755436, 9413223636 Visit us at : www.fluxeducare.in
CORE JAVA PROGRAMMING
We can apply equality operators for every primitive type (1) & - If both operands are true then result is true.
including Boolean types.
(2) | -If at least 1 operand is true then result is true.
Example
(3) ^ - If both operands are different then result is
1. 10 == 10.0 true.
We can apply equality operators even for object We can apply these operators even for integral data
reference also. types also.
For the two object reference r1 and r2, r1 = r2 returns (1) S.o.pln(4&5) ; 4
true if both r1 , and r2 are pointing to the same object.
(2) S.o.pln(4|5) ; 5
i.e, equality operator is always meant for reference /
address comparison. (3) S.o.pln(4^5) ; 1
Example
Example
(1) S.o.p(!4);
H.O. : B-5,Dev nagar ,opp. Kamal & company ,gopalpura ,Jaipur Tel : 0141-2708941 , Mob : 9887755436, 9413223636 Visit us at : www.fluxeducare.in
CORE JAVA PROGRAMMING
Logical operators are && and ||. The only ternary operator available in java is a ternary
operator or conditional operator.
We can use these operators just to improve
performance of the system. These are exactly same as Example
normal bitwise operators & , | except the following
difference int a=10 , b=20
Example
(1) x&&y = y will be evaluated if x is true.
int a=10 , b =20 ;
(2) x||y = y will be evaluated if x is false.
Int x=(a>50)?777((b>100)?888:999)):
Example:
S.o.pln.(x);999
int x=10;
int y=15;
11. New operator:
if (++x>10 & ++y<15)
We can use this operator for creation of objects.
++x;
In java there is no delete operator because distraction of
else
useless object is responsibility of garbage collector.
++y:
H.O. : B-5,Dev nagar ,opp. Kamal & company ,gopalpura ,Jaipur Tel : 0141-2708941 , Mob : 9887755436, 9413223636 Visit us at : www.fluxeducare.in
CORE JAVA PROGRAMMING
The following are various possible implicit type casting Operator precedence
Example &&,||
2.byte b =(byte)130;
S.o.p(b); -126
Example
double d = 130.456;
int a =(int) d ;
byte b = (byte) d ;
S.o.pln(a); 130
S.o.pln(b); -126
H.O. : B-5,Dev nagar ,opp. Kamal & company ,gopalpura ,Jaipur Tel : 0141-2708941 , Mob : 9887755436, 9413223636 Visit us at : www.fluxeducare.in
CORE JAVA PROGRAMMING
Flow control describe the order in which the statement if several options are possible then it is never
will be executed at runtime. recommended to use if-else, we should go for switch
statements.
Syntax:
switch(x)
case 1 : action1;
i. simple if }
ii if else Note:
iv Ladder else if (ii) Both case and default are optional inside a switch
(ii) curly brackets are options and without curly we can use default case to define default action. It will
brackets we can take only one statement which should be executed if no other case is matched. we can take
not be declarative statement. default case anywhere within the switch but it is
conversion to take as last case.
H.O. : B-5,Dev nagar ,opp. Kamal & company ,gopalpura ,Jaipur Tel : 0141-2708941 , Mob : 9887755436, 9413223636 Visit us at : www.fluxeducare.in
CORE JAVA PROGRAMMING
Three-dimensional array
int[][][] a;
int [][][]a;
int a[][][]; int[][][] a=new int[2][][];
int[] [][]a; a[0]=new int[3][];
int[] a[][]; a[0][0]=new int[1];
int[] []a[]; a[0][1]=new int[2];
int[][] []a; a[0][2]=new int[3];
int[][] a[]; a[1]=new int[2][2];
int []a[][];
int [][]a[];
Note
If we want to specify the dimension before the variable
that rule is applicable only for the 1st variable.
Second variable onwards we can't apply in the same
declaration.
Example:
1. int[] a1,b1; //a-1,b-1 (valid)
2) int[] a2[],b2; //a-2,b-1 (valid)
3) int[] []a3,b3; //a-2,b-2 (valid)
4) int[] a,[]b; //C.E: expected (invalid)
H.O. : B-5,Dev nagar ,opp. Kamal & company ,gopalpura ,Jaipur Tel : 0141-2708941 , Mob : 9887755436, 9413223636 Visit us at : www.fluxeducare.in
CORE JAVA PROGRAMMING
Array Initialization
int[][] a={{10,20,30},{40,50}};
int[][][]
a={{{10,20,30},{40,50}},{{60},{70,80},{90
,100,110}}};
length
Example:
H.O. : B-5,Dev nagar ,opp. Kamal & company ,gopalpura ,Jaipur Tel : 0141-2708941 , Mob : 9887755436, 9413223636 Visit us at : www.fluxeducare.in
CORE JAVA PROGRAMMING
TYPES OF VARIABLES
{
Based on the purpose and position of declaration all
variables are divided into 3 types: System. Out. Println(x);
Instance variables should be declared with in the class Test t=new Test();
directly, both outside of any method or block or
constructor. System. Out. Println(t.s); null
Instance variables cannot be accessed from static area System. Out. Println(t.x); 0
directly we can access by using object reference.
System. Out. Println(t.b); false
Instance variables also known as “Object level
variables” or “attributes”. }
H.O. : B-5,Dev nagar ,opp. Kamal & company ,gopalpura ,Jaipur Tel : 0141-2708941 , Mob : 9887755436, 9413223636 Visit us at : www.fluxeducare.in
CORE JAVA PROGRAMMING
Static variables Static variables are created at the time of class loading.
Hence, we can access from both instance and static
If the value of the variable is not varied from object to areas directly.
object then it is never recommended to declare that
variable as object level, we have to declare such types of Example: -
variables at class level by using Static modifier.
Class Test
In the case of instance variables foe every object a
separate copy will be created, but in the case of static {
variable single copy will be created, but in the case of
static variable single copy will be created at class level static Int x=10;
and the copy will be shared by all objects of that class.
Public static void main(String[] args)
Static variables will be created at the time of class
{
loading and destroy at the time of class unloading. Here
the scope of the static variables is exactly same as the System. Out. Println(x);
scope of the class.
}
Static variables should be declared with in the class
directly with static modifier. Public static void main()
Within the same class even it’s not required to use class }
name. Also we can access directly.
}
Example
For the static variables it is not required to perform
Class Test initialization explicitly, compulsory JVM will provide
default values.
{
Example:
static int x=10;
Class Test
Public static void main(String[] args)
{
{
Static Int x;
System. out. println(Test.x);
Public static void main(String[] args)
System. out. println(x);
{
Test t=new Test();
System. Out. Println(x);
System. Out. println(t.x);
}
}
}
}
Static variables will be started in method area. Static
variables also known as “Class-level variables” or
“fields”.
H.O. : B-5,Dev nagar ,opp. Kamal & company ,gopalpura ,Jaipur Tel : 0141-2708941 , Mob : 9887755436, 9413223636 Visit us at : www.fluxeducare.in
CORE JAVA PROGRAMMING
Local variables will be started inside a stack. o The only applicable modifier for the local variables is
“final”. If we are using any other modifier, we can get
The local variables will be created while executing the compile the error.
block in which we declared it and destroyed once the
block completed. Hence, the scope of local variables is
executively same as the block in which we declared it.
Example:
Class Test
Int x;
If(args.length>0)
x=10;
Else
X=20;
OUTPUT: -
Java test- 20
Java test x y- 10
H.O. : B-5,Dev nagar ,opp. Kamal & company ,gopalpura ,Jaipur Tel : 0141-2708941 , Mob : 9887755436, 9413223636 Visit us at : www.fluxeducare.in
CORE JAVA PROGRAMMING
Inside the classes it is not possible to write the business 1. Instance method
logics directly, so inside the class declares the method
inside that method writes the logics of the application. 2. Static method
Modifiers-list ---> represent access permissions. Method defined in a class which is only accessible
through the Object of the class are called Instance
Return-type ---> functionality return value method.
Throws Exception ---> representing exception handling void m1() //instance method
H.O. : B-5,Dev nagar ,opp. Kamal & company ,gopalpura ,Jaipur Tel : 0141-2708941 , Mob : 9887755436, 9413223636 Visit us at : www.fluxeducare.in
CORE JAVA PROGRAMMING
The main advantage of static method is object is not Instance & static methods with parameters.
required to call a static method. If it were a non-static
method, JVM creates an object first then call static If the method is expecting parameters (inputs to
method that will lead the problem of extra memory functionality), while calling that method must pass the
allocation. values to parameters.
//static area
} class Test
System.out.println(a);
{ {
{ System.out.println(str);
} System.out.println(d);
} System.out.println(“m3 method”);
{ System.out.println(b);
Test.m2(); {
} t.m1(10,'a');
Test.m2(“ratan”,true,10.5);
int x=100;
H.O. : B-5,Dev nagar ,opp. Kamal & company ,gopalpura ,Jaipur Tel : 0141-2708941 , Mob : 9887755436, 9413223636 Visit us at : www.fluxeducare.in
CORE JAVA PROGRAMMING
t.m3(x,y); {
} int x = t.m1();
Java methods return type is mandatory & void System.out.println("m2 method return value="+b);
represents no return value. Methods can have any
return type like primitive type such as byte, short, int, String str = t.m3();
long, float & Arrays type , Class type , Interface type
,Enum type….etc System.out.println("m3 method return value="+str);
Method is able to returns the value, it is recommended 1. Hold the return value & print that value.
to hold the return value check the status of the method
but it is optional. 2. Directly print the value by calling method using
System.out.println()
class Test
{
class Test
int m1()
{
{
int m1()
System.out.println("m1 method");
{
return 10;
System.out.println("m1 method");
}
return 10;
static boolean m2()
}
{
public static void main(String[] args)
System.out.println("m2 method");
{
return false;
Test t =new Test();
}
int x = t.m1();
String m3()
System.out.println("return value="+x); //1-way
{
System.out.println("return value="+t.m1()); //2-way
System.out.println("m3 method");
}
return "flux";
}
}
H.O. : B-5,Dev nagar ,opp. Kamal & company ,gopalpura ,Jaipur Tel : 0141-2708941 , Mob : 9887755436, 9413223636 Visit us at : www.fluxeducare.in
CORE JAVA PROGRAMMING
Although Java is strictly pass by value, the precise There is only call by value in java, not call by reference.
effect differs between whether a primitive type or a If we call a method passing a value, it is known as call
reference type is passed. by value. The changes being done in the called method,
is not affected in the calling method.
When we pass a primitive type to a method, it is passed
by value. But when we pass an object to a method, the Call by value example:
situation changes dramatically, because objects are
passed by what is effectively call-by-reference. Java class Operation
does this interesting thing that’s sort of a hybrid
between pass-by-value and pass-by-reference. {
Basically, a parameter cannot be changed by the
int data=50;
function, but the function can ask the parameter to
change itself via calling some method within it. void change(int data){
op.change(500);
class Operation2
int data=50;
op.data=op.data+100;
op.change(op);//passing object
} }
H.O. : B-5,Dev nagar ,opp. Kamal & company ,gopalpura ,Jaipur Tel : 0141-2708941 , Mob : 9887755436, 9413223636 Visit us at : www.fluxeducare.in
CORE JAVA PROGRAMMING
If the application contains both instance & local We may invoke the method of the current class by using
variables with same name, in this case to represent the this keyword. If we don't use the this keyword,
instance variables we have two approaches. compiler automatically adds this keyword while
invoking the method.
1. Access by using this keyword
class A
2. Access by using object.
{
void m()
class Test
{
{
System.out.println("hello m");}
int a=100,b=200;
void n()
void add(int a,int b)
{
{
System.out.println("hello n");
System.out.println(a+b);
this.m(); //m() same as this.m()
System.out.println(this.a+this.b); //approach-1
}
Test t = new Test();
}
System.out.println(t.a+t.b); //approach-2
class TestThis4
}
{
public static void main(String[] args)
public static void main(String args[]){
{
A a=new A();
Test t = new Test();
a.n();
t.add(10,20);
}
}
}
}
H.O. : B-5,Dev nagar ,opp. Kamal & company ,gopalpura ,Jaipur Tel : 0141-2708941 , Mob : 9887755436, 9413223636 Visit us at : www.fluxeducare.in
CORE JAVA PROGRAMMING
class S2
System.out.println("method is invoked");
void p()
m(this);
S2 s1 = new S2();
s1.p();
H.O. : B-5,Dev nagar ,opp. Kamal & company ,gopalpura ,Jaipur Tel : 0141-2708941 , Mob : 9887755436, 9413223636 Visit us at : www.fluxeducare.in
CORE JAVA PROGRAMMING
CONSTRUCTOR t.m1();
(3) Constructor not allowed explicit return type even User defined constructor:
void.
Constructors are used to write the logics these logics
are executed during object creation. Method also used
to write the logics these logics are executed when we
There are two types of constructors, call the method. The constructor arguments are local
variables.
(1) Default Constructor
class Test
(2) User defined Constructor or parameterized
constructor {
void m1()
Default Constructor: {
Inside the class if we are not declaring any constructor System.out.println(“m1 method”);
then compiler generates zero argument constructors
with empty implementation at the time of compilation is }
called default constructor.
Test()
The compiler generated constructor is called default
{
constructor. Inside the class default constructor is
invisible mode. System.out.println("0-arg constructor");
class Test }
{ Test(int i)
void m1() {
{ System.out.println("1-arg constructor");
System.out.println("m1 method"); }
H.O. : B-5,Dev nagar ,opp. Kamal & company ,gopalpura ,Jaipur Tel : 0141-2708941 , Mob : 9887755436, 9413223636 Visit us at : www.fluxeducare.in
CORE JAVA PROGRAMMING
Test()
Note: {
{ }
Test t1=new Test(); //error : inside the class no 0-arg Constructor is a special method used to initialize the
constructor object.
Constructor calling:
Test()
{ System.out.println("0 arg");
this(10);
H.O. : B-5,Dev nagar ,opp. Kamal & company ,gopalpura ,Jaipur Tel : 0141-2708941 , Mob : 9887755436, 9413223636 Visit us at : www.fluxeducare.in
CORE JAVA PROGRAMMING
STATIC BLCOK
Output:
20
Main method
H.O. : B-5,Dev nagar ,opp. Kamal & company ,gopalpura ,Jaipur Tel : 0141-2708941 , Mob : 9887755436, 9413223636 Visit us at : www.fluxeducare.in
CORE JAVA PROGRAMMING
{ class Emp
static {
{
static int eid;
System.out.println("static block-1");
static
}
{
static
eid=111;
{
}
System.out.println("static block-2");
static void disp()
}
{
Test()
System.out.println(eid);
{
System.out.println("0-arg cons"); }
Test(int a) {
{ Emp.disp();
System.out.println("1-arg cons"); }
}
}
public static void main(String[] args)
new Test();
new Test(10);
H.O. : B-5,Dev nagar ,opp. Kamal & company ,gopalpura ,Jaipur Tel : 0141-2708941 , Mob : 9887755436, 9413223636 Visit us at : www.fluxeducare.in
CORE JAVA PROGRAMMING
{
Whenever we are executing a java class static control
//logics here flow will be executed. In the Static control flow
Whenever we are creating an object the following
}
sequence of events will be performed automatically.
Instance blocks execution depends on object creation it
1. Identification of instance members from top to
means if we are creating 10 objects 10 times instance
bottom(3 to 8).
blocks are executed.
2. Execution of instance variable assignments and
Inside the class it is possible to declare the more than
instance blocks from top to bottom(9 to 14).
one instance block the execution order is top to bottom.
3. Execution of constructor.
Note:
class Test
{
{
System.out.println("instance block:logics-1");
}
{
System.out.println("instance block:logics-2");
}
Test()
{
System.out.println("0-arg cons");
}
Test(int a)
{
System.out.println("1-arg cons ");
}
public static void main(String[] args)
{
new Test();
new Test(10);
}
}
H.O. : B-5,Dev nagar ,opp. Kamal & company ,gopalpura ,Jaipur Tel : 0141-2708941 , Mob : 9887755436, 9413223636 Visit us at : www.fluxeducare.in
CORE JAVA PROGRAMMING
class Emp
{
int eid;
{
eid=111;} //instance block
Emp()
{
eid=222; } //constructor
void disp()
{
System.out.println("emp id="+eid);
}
public static void main(String[] args)
{
new Emp().disp();
}
}
class Test
{
{
System.out.println("instance block");
} //instance block
int a=m1(); //instance variables
int m1()
{
System.out.println("m1() method called by variable");
return 100;
}
public static void main(String[] args)
{
new Test();
}
}
H.O. : B-5,Dev nagar ,opp. Kamal & company ,gopalpura ,Jaipur Tel : 0141-2708941 , Mob : 9887755436, 9413223636 Visit us at : www.fluxeducare.in
CORE JAVA PROGRAMMING
}
Compile time polymorphism
void m1(float f)
There are three types of overloading in java,
{
a. Method overloading
System.out.println("float argument");
b. Constructor overloading
}
c. Operator overloading
public static void main(String[] args)
{
Method Overloading
Test t=new Test();
If a class contains more than one method with same
name but different number of arguments or same t.m1(10,20l);
number of arguments but different data types those
methods are called overloaded methods. t.m1(10,20);
Note:
H.O. : B-5,Dev nagar ,opp. Kamal & company ,gopalpura ,Jaipur Tel : 0141-2708941 , Mob : 9887755436, 9413223636 Visit us at : www.fluxeducare.in
CORE JAVA PROGRAMMING
If the class contains more than one constructors with One operator with different behaviors is called
same name but different arguments or same number of Operator overloading.
arguments with different data types those constructors
are called overloaded constructors. Java is not supporting operator overloading but only
one overloaded in java language is ‘+’.
class Test
If both operands are integer then “+” performs
{ addition.
new Test(10);
new Test('a',100);
new Test('r');
H.O. : B-5,Dev nagar ,opp. Kamal & company ,gopalpura ,Jaipur Tel : 0141-2708941 , Mob : 9887755436, 9413223636 Visit us at : www.fluxeducare.in
CORE JAVA PROGRAMMING
INHERITANCE
Javap full-class-name }
Types of inheritance
H.O. : B-5,Dev nagar ,opp. Kamal & company ,gopalpura ,Jaipur Tel : 0141-2708941 , Mob : 9887755436, 9413223636 Visit us at : www.fluxeducare.in
CORE JAVA PROGRAMMING
1. Whatever the parent has by default available to the To achieve method overloading one java class sufficient
child but whatever the child has by default not available but to achieve method overriding we required two java
to the parent. Hence on the child reference we can call classes with parent and child relationship.
both parent and child class methods. But on the parent
reference we can call only methods available in the In method overriding method implementations already
parent class and we can't call child specific methods. present in parent class, If the child class required that
implementation then access those implementations. If
2. Parent class reference can be used to hold child class the child class not required parent class method
object but by using that reference we can call only implementations then override parent class method in
methods available in parent class and child specific child class to write the child specific implementations.
methods we can't call.
In overriding parent class method is called overridden
3. Child class reference cannot be used to hold parent method and Child class method is called overriding
class object. method.
The final keyword in java is used to restrict the user. class Parent
The java final keyword can be used for: {
void property()
(1) variable {
System.out.println("money+land+hhouse");
(2) method }
void marry() //overridden method
{
(3) class
System.out.println("black girl");
}
(1) Java final variable
}
class Child extends Parent
If we make any variable as final, we cannot change the {
value of final variable i.e. It will be constant. void marry() //overriding method
{
System.out.println("white girl/red girl");
}
(2) Java final method public static void main(String[] args)
{
If we make any method as final, we cannot override it. Child c=new Child();
c.property();
c.marry();
}
(3) Java final class }
H.O. : B-5,Dev nagar ,opp. Kamal & company ,gopalpura ,Jaipur Tel : 0141-2708941 , Mob : 9887755436, 9413223636 Visit us at : www.fluxeducare.in
CORE JAVA PROGRAMMING
Rule 1 Rule 3
While overriding methods the overridden method While overriding methods it is possible to change the
signature and overriding method signature must be return type of overridden method & overriding methods
same. at class leel by using co-variant return type concept.
void marry(){ } //overridden method Co-variant return type: overridden method return
type is parent type & overriding method return type is
} child type.
class Child extends Parent class Animal
{
{
}
void marry(){ } //overriding method class Dog extends Animal{}
class Parent
} {
Animal m1()
{
System.out.println("parent m1");
return new Animal();
}
Rule 2
}
class Child extends Parent
While overriding method overridden method return type
{
& overriding method return type must be same at
Dog m1()
primitive level(byte, int, double, boolea etc) otherwise
{
compiler will generate error message.
System.out.println("child m1");
class Parent return new Dog();
}
{ public static void main(String[] args)
{
void marry(){ } //overridden method Child c = new Child();
Dog d = c.m1();
} }
}
class Child extends Parent
{ Rule 4
In java while overriding it is possible to maintain same
int marry(){ } //overriding method level(public-public) permission or increasing
order(default-public) but it is not possible to
}; decrease(public-default) the permission.
In java if we are trying to decrease the permission
compilation error:- marry() in Child cannot override compiler will generate error message “attempting to
marry() in Parent return type int is not compatible with assign weaker access privileges”.
void
Case 1: same level Valid [public-public]
class Parent
{
public void m1()
{
System.out.println("m1 method");}
}
class Child extends Parent
{
public void m1()
{
System.out.println("m1 method");}
}
H.O. : B-5,Dev nagar ,opp. Kamal & company ,gopalpura ,Jaipur Tel : 0141-2708941 , Mob : 9887755436, 9413223636 Visit us at : www.fluxeducare.in
CORE JAVA PROGRAMMING
SUPER KEYWORD
Case 2: increasing permission valid [protected-public] “this” keyword is used to represent current class object,
class Parent “super” represent super class object.
{ Inside the static area both this, super keywords are not
protected void m1() allowed.
{ Super keyword is used for:
System.out.println("m1 method"); 1. Super class variables
} 2. Super class methods
} 3. Super class constructors
class Child extends Parent 4. Super class instance blocks
{ 5. Super class static blocks
public void m1()
{ super class variables calling
System.out.println("m1 method"); class Parent
} {
} int a=10,b=20;
}
Case3: decreasing permission Invalid [public-protected] class Child extends Parent
class Parent {
{ int a=100;
public void m1() int b=200;
{ void m1(int a,int b) //local variables
System.out.println("m1 method"); {
} System.out.println(a+b); //local variables addition
} System.out.println(this.a+this.b);//current class
class Child extends Parent variables addition
{ System.out.println(super.a+super.b); //super class
protected void m1() variables addition
{ }
System.out.println("m1 method"); public static void main(String[] args)
} {
} new Child().m1(1000,2000);
}
}
H.O. : B-5,Dev nagar ,opp. Kamal & company ,gopalpura ,Jaipur Tel : 0141-2708941 , Mob : 9887755436, 9413223636 Visit us at : www.fluxeducare.in
CORE JAVA PROGRAMMING
case 1 Case 2
To call the current class constructors use this keyword Inside the constructor super keyword must be first
& call super class constructor use super keyword. statement otherwise compiler generates error message
“call to super must be first line in constructor”.
super() ----> super class 0-arg constructor calling
Child(int a)
super(10) ----> super class 1-arg constructor calling
{
super(10,20) ----> super class 2-arg constructor calling
System.out.println("child 1-arg constructor--->"+a);
class Parent
super(); //(compilation Error)
{
}
Parent()
Case 3:
{
Inside the constructor it is possible to use either this
System.out.println("parent 0-arg constructor"); keyword or super keyword but,
class Child extends Parent Both super & this keyword also not allowed.
{ Case 4:
H.O. : B-5,Dev nagar ,opp. Kamal & company ,gopalpura ,Jaipur Tel : 0141-2708941 , Mob : 9887755436, 9413223636 Visit us at : www.fluxeducare.in
CORE JAVA PROGRAMMING
Inside the constructor if we are not declaring this or In parent and child relationship first parent class
super keyword then compiler generate super keyword at instance blocks are executed then child class instance
first line of the constructor. The compiler generated blocks are executed.
super keyword is always 0-arg constructor calling.
class Parent
class Parent {
{
{ System.out.println("parent instance block"); }
}
Parent() class Child extends Parent
{
{
{
System.out.println("parent 0-arg cons"); System.out.println("Child instance block");
}
} public static void main(String[] args)
{
} new Child();
}
class Child extends Parent }
Child()
Super class static blocks
{
In parent and child relationship first parent class static
//super(); generated by compiler
blocks are executed only one time then child class static
blocks are executed only one time because static blocks
System.out.println("Child 0-arg constructor");
are executed with respect to .class loading. Instance
} block execution depends on object creation & static
block execution depends on class loading.
Child(int a)
class Parent
{ {
static
//super(); generated by compiler {
System.out.println("parent static block");
System.out.println("child 1-arg cons"); } //static block
}
}
class Child extends Parent
public static void main(String[] args) {
static
{ {
System.out.println("child static block");
new Child(); } //static block
public static void main(String[] args)
new Child(10); {
}
} }
}
H.O. : B-5,Dev nagar ,opp. Kamal & company ,gopalpura ,Jaipur Tel : 0141-2708941 , Mob : 9887755436, 9413223636 Visit us at : www.fluxeducare.in
CORE JAVA PROGRAMMING
class B extends A
{
void m1()
{
System.out.println("Inside B's m1 method");
}
}
class C extends A
{
void m1()
{
System.out.println("Inside C's m1 method");
}
}
class Dispatch
{
public static void main(String args[])
{
A a = new A();
B b = new B();
C c = new C();
A ref;
ref = a;
ref.m1();
H.O. : B-5,Dev nagar ,opp. Kamal & company ,gopalpura ,Jaipur Tel : 0141-2708941 , Mob : 9887755436, 9413223636 Visit us at : www.fluxeducare.in
CORE JAVA PROGRAMMING
For any java class if we are not allowed to create an class Parent
object such type of class, we have to declare with
abstract modifier that is for abstract class instantiation {
is not possible.
public void methodOne();
}
ABSTRACT METHODS
Output: Compile time error.
The abstract method contains only method declaration
but not implementation.
Example: {
Case 1: {
The class contains at least one abstract method is public abstract void methodOne();
called abstract class.
}
abstract class Test
Output:
{ void m1(){body}
Compile time error.
void m2(){body}
Case 2:
void m1(){body}
void m2(){body}
void m3(){body}
H.O. : B-5,Dev nagar ,opp. Kamal & company ,gopalpura ,Jaipur Tel : 0141-2708941 , Mob : 9887755436, 9413223636 Visit us at : www.fluxeducare.in
CORE JAVA PROGRAMMING
{ {
} t.m2();
{ t.m4();
} }
Output:
Compile time error. Inside the abstract class it is possible to declare the
constructor.
H.O. : B-5,Dev nagar ,opp. Kamal & company ,gopalpura ,Jaipur Tel : 0141-2708941 , Mob : 9887755436, 9413223636 Visit us at : www.fluxeducare.in
CORE JAVA PROGRAMMING
The interfaces are extension of abstract classes. The • It is not possible to create the object of interface.
abstract class contains abstract methods & normal • Inside the interface constructor declaration not
methods. The interface allows to declare only abstract allowed.
methods (up to 1.7 version) • All methods in interfaces are by default public and
abstract.
Interfaces are used to declare the functionality • One class can extends only one class but one
declarations but not definition. Interfaces are used to interface is able to extend more than one interface.
achieve full abstraction. Interface is similar to class it is
• Interface contains only static fields but not instance
a collection of abstract methods. For the interfaces
fields.
compiler will generate .class files after compilation
• Interfaces can’t extends by class it is implemented
Declare the interface by using interface keyword. by interface.
Syntax:
H.O. : B-5,Dev nagar ,opp. Kamal & company ,gopalpura ,Jaipur Tel : 0141-2708941 , Mob : 9887755436, 9413223636 Visit us at : www.fluxeducare.in
CORE JAVA PROGRAMMING
{ {
} }
{ {
t.m1(); }
t.m3(); {
i.m2(); }
i.m3(); }
} Important points
Example:
interface It
void m1();
void m2();
void m3();
H.O. : B-5,Dev nagar ,opp. Kamal & company ,gopalpura ,Jaipur Tel : 0141-2708941 , Mob : 9887755436, 9413223636 Visit us at : www.fluxeducare.in
CORE JAVA PROGRAMMING
System.out.println("m1 method");
a=a+10;
System.out.println(a);
t.m1();
H.O. : B-5,Dev nagar ,opp. Kamal & company ,gopalpura ,Jaipur Tel : 0141-2708941 , Mob : 9887755436, 9413223636 Visit us at : www.fluxeducare.in
CORE JAVA PROGRAMMING
packages
Example 2: (Invalid)
classes & interfaces
import java.io.*;
methods & variables
package com.flux;
java is open-source technology and it is possible to
check source code of the java. The source code location
C:\Program Files\Java\jdk1.7.0_75\src(zip file) extract
Creation of package
the zip file. Java contains 14 predefined packages but
the default package in java if java.lang. package. Step-1: write the application with package statement.
1) Predefined packages. }
Predefined packages: {
The packages which are defined by user, and these Step-2: compilation process
packages contains user defined classes and interfaces.
If the source file contains the package statement then
Declare the package by using package keyword. compile that application by using following command.
Inside the source file it is possible to declare only one Test.java ---> source file name
package statement and that statement must be first
statement of the source file.
H.O. : B-5,Dev nagar ,opp. Kamal & company ,gopalpura ,Jaipur Tel : 0141-2708941 , Mob : 9887755436, 9413223636 Visit us at : www.fluxeducare.in
CORE JAVA PROGRAMMING
java flux.Test
package flux.educare;
H.O. : B-5,Dev nagar ,opp. Kamal & company ,gopalpura ,Jaipur Tel : 0141-2708941 , Mob : 9887755436, 9413223636 Visit us at : www.fluxeducare.in
CORE JAVA PROGRAMMING
import flux.educare.Bca;
class Usepackage
{
public static void main(String args[])
{
Bca obj=new Bca(2,3,4);
obj.show();
obj.Add();
}
H.O. : B-5,Dev nagar ,opp. Kamal & company ,gopalpura ,Jaipur Tel : 0141-2708941 , Mob : 9887755436, 9413223636 Visit us at : www.fluxeducare.in
CORE JAVA PROGRAMMING
An exception is an event that occurs during execution The exceptions which are not checked by the compiler
of the program that disturbs normal flow of the program are called unchecked Exception.
instructions.
ArithmeticException,
An unexpected even that disturbs the normal ArrayIndexOutOfBoundsException,
termination of the application is called exception. In NumberFormatException….etc
application whenever the exception occurred,
The classes that extends RuntimeException class are
1. Program terminated abnormally called unchecked exceptions.
System.out.println(a[5]);
Exception Handling java.lang.ArrayIndexOutOfBoundsExcepti
on: 5
The main objective of exception handling is,
System.out.println("ratan".charAt(12));
a. To get normal termination of the application java.lang.StringIndexOutOfBoundsExcepti
on
b. To execute the rest of the application code.
}
Exception handling means just we are providing
alternate code to continue the execution of remaining }
code & to get normal termination of the application.
Every Exception is a predefined class present in
different packages.
If the application contains un-checked Exception code
If the application contains un-checked Exception code
is compiled but at runtime JVM display exception
is compiled but at runtime JVM display
message & program terminated abnormally. To
exception message & program terminated abnormally. overcome runtime problem must handle the exception
either using try-catch blocks or by using throws
To overcome runtime problem must handle the keyword.
exception either using try-catch blocks or by using
throws keyword.
Checked Exception
Types of Exceptions The Exceptions which are checked by the compiler are
called Checked Exceptions.
The Exceptions are divided into three types
IOException, SQLException,
1) Checked Exception InterruptedException……..etc
2) Unchecked Exception The classes that extends Exception class are called
checked exceptions.
3) Error
H.O. : B-5,Dev nagar ,opp. Kamal & company ,gopalpura ,Jaipur Tel : 0141-2708941 , Mob : 9887755436, 9413223636 Visit us at : www.fluxeducare.in
CORE JAVA PROGRAMMING
Whether it is a checked Exception or unchecked In our program the code which may raise exception is
exception exceptions are raised at runtime but not called risky code, we have to place risky code inside try
compile time. block and the corresponding handling code inside catch
block.
whether it is a checked Exception or unchecked
Exception must handle the Exception by using try-
catch blocks or throws keyword to get normal
try
termination of application & to execute rest of the
{
application.
Risky code
}
catch(Exception e)
{
Handling code
}
class Test
{
public static void main(String[] args){
System.out.println("statement1");
System.out.println(10/0);
System.out.println("statement3");
}
}
output:
statement1
RE:AE:/by zero at Test.main()
Abnormal termination.
The root class of exception handling is Throwable class.
With try catch
In above tree Structure RuntimeException its child
classes & Error its child classes are Unchecked
remaining all exceptions are checked Exceptions. class Test{
public static void main(String[] args){
System.out.println("statement1");
try{
Exception Handling keywords
System.out.println(10/0);
1. Try }
catch(ArithmeticException e){
2. Catch System.out.println(10/2);
}
3. Finally System.out.println("statement3");
}}
4. Throws Output:
statement1
5. Throw 5
statement3
Normal termination.
H.O. : B-5,Dev nagar ,opp. Kamal & company ,gopalpura ,Jaipur Tel : 0141-2708941 , Mob : 9887755436, 9413223636 Visit us at : www.fluxeducare.in
CORE JAVA PROGRAMMING
1. Within the try block if anywhere an exception raised The way of handling an exception is varied from
then rest of the try block won't be executed even though exception to exception. Hence for every exception type it
we handled that exception. Hence we have to place/take is recommended to take a separate catch block. That is
only risk code inside try block and length of the try try with multiple catch blocks is possible and
block should be as less as possible. recommended to use.
getMessage(): Note:
This method returns only description of the exception. If try with multiple catch blocks present then order of
catch blocks is very important. It should be from child
Description to parent by mistake if we are taking from parent to
child then we will get Compile time error saying
"exception xxx has already been caught"
H.O. : B-5,Dev nagar ,opp. Kamal & company ,gopalpura ,Jaipur Tel : 0141-2708941 , Mob : 9887755436, 9413223636 Visit us at : www.fluxeducare.in
CORE JAVA PROGRAMMING
Finally block
H.O. : B-5,Dev nagar ,opp. Kamal & company ,gopalpura ,Jaipur Tel : 0141-2708941 , Mob : 9887755436, 9413223636 Visit us at : www.fluxeducare.in
CORE JAVA PROGRAMMING
class Test
{
Case-3: If an exception raised but the corresponding public static void main(String[] args){
catch block not matched: throw new ArithmeticException("/
by zero");
}
class Test }
{ In this case we are creating exception
public static void main(String[] args) object explicitly and handover to the
{ JVM manually.
try
{
System.out.println("try block executed");
System.out.println(10/0);
}
catch(NullPointerException e) Note:
{
System.out.println("catch block executed"); After throw statement we can't take any statement
}
directly otherwise we will get compile time error saying
finally
unreachable statement.
{
System.out.println("finally block executed");
}
}
}
Output:
Try block executed
Finally block executed
Exception in thread "main"
java.lang.ArithmeticException: / by zero
atTest.main(Test.java:8)
H.O. : B-5,Dev nagar ,opp. Kamal & company ,gopalpura ,Jaipur Tel : 0141-2708941 , Mob : 9887755436, 9413223636 Visit us at : www.fluxeducare.in
CORE JAVA PROGRAMMING
We can use throw keyword only for Throwable types "throws" keyword required only checked exceptions.
otherwise we will get compile time error saying Usage of throws for unchecked exception there is no
incomputable types. use.
class Test3
{
public static void
main(String[] args)
{
try{
Thread.sleep(5000);
}
catch(InterruptedException
e){}
}
}
Output:
Compile and running successfully
H.O. : B-5,Dev nagar ,opp. Kamal & company ,gopalpura ,Jaipur Tel : 0141-2708941 , Mob : 9887755436, 9413223636 Visit us at : www.fluxeducare.in
CORE JAVA PROGRAMMING
class Test Sometimes we can create our own exception to meet our
{ programming requirements. Such type of exceptions are
public static void main(String[] args)throws called customized exceptions (user defined exceptions).
InterruptedException
{
Thread.sleep(5000); class TooYoungException extends
} RuntimeException
} {
Output: TooYoungException(String s)
Compile and running successfully {
super(s);
}
}
class Test class TooOldException extends
{ RuntimeException
void studentDetails() throws {
InterruptedException TooOldException(String s)
{ {
System.out.println("Rahul is sleeping"); super(s);
Thread.sleep(3000); }
System.out.println("do not disturb sir......"); }
} class CustomizedExceptionDemo
void hod()throws InterruptedException {
{ public static void main(String[] args)
studentDetails(); {
} int age=Integer.parseInt(args[0]);
void principal() if(age>60)
{ {
try{ throw new TooYoungException("please wait
hod(); some more time.... u will get best
} match");
catch(InterruptedException ie) }
{ else if(age<18)
ie.printStackTrace(); {
} throw new TooOldException("u r age already
} crossed....no chance of getting
void officeBoy() married");
{ }
principal(); else
} {
public static void main(String[] args) System.out.println("you will get match details
{ soon by e-mail");
Test t = new Test(); }}}
t.officeBoy();
}
}
H.O. : B-5,Dev nagar ,opp. Kamal & company ,gopalpura ,Jaipur Tel : 0141-2708941 , Mob : 9887755436, 9413223636 Visit us at : www.fluxeducare.in
CORE JAVA PROGRAMMING
String Note:
String is a sequence of characters. But in Java, string is When ever we are using new operator compulsory a new
an object that represents a sequence of characters. The object will be created on the Heap. There may be a
java.lang.String class is used to create a string object. chance of existing two objects with same content on the
heap but there is no chance of existing two objects with
Once we create a String object we can't perform any same content on SCP . i.e., duplicate objects possible in
changes in the existing object. If we are try to perform the heap but not in SCP .
any changes with those changes a new object will be
created. This behavior is called immutability of the Example :
String object.
String s1=new String("bhaskar");
There are two ways to create String object:
String s2=new String("bhaskar");
1. By string literal
String s3="bhaskar";
2. By new keyword
String s4="bhaskar";
1) String Literal
String s="flux";
String s2="flux";//It doesn't create a new instance Creates an empty String Object.
In the above example, only one object will be created. 2. String s=new String(String literals);
Firstly, JVM will not find any string object with the
value "flux" in string constant pool, that is why it will To create an equivalent String object for the given
create a new object. After that it will find the string with String literal on the heap.
the value "flux" in the pool, it will not create a new
object but will return the reference to the same 3. String s=new String(StringBuffer sb);
instance.
Creates an equivalent String object for the given
Note: StringBuffer.
String objects are stored in a special memory area 4. String s=new String(char[] ch);
known as the "string constant pool".
creates an equivalent String object for the given char[ ]
2) By new keyword array.
In such case, JVM will create a new string object in public static void main(String[] args) {
normal (non-pool) heap memory, and the literal "flux"
char[] ch={'a','b','c'} ;
will be placed in the string constant pool. The variable s
will refer to the object in a heap (non-pool).
String s=new String(ch);
System.out.println(ch);//abc
}}
H.O. : B-5,Dev nagar ,opp. Kamal & company ,gopalpura ,Jaipur Tel : 0141-2708941 , Mob : 9887755436, 9413223636 Visit us at : www.fluxeducare.in
CORE JAVA PROGRAMMING
Create an equivalent String object for the given byte[] For content comparison where case is important.
array.
It is the overriding version of Object class .equals()
Example: method.
public static void main(String[] args) { For content comparison where case is not important.
}} String s="java";
System.out.println(s.equals("JAVA"));//false
class StringDemo { Return the substring from begin index to end of the
string.
public static void main(String[] args) {
Example:
String s="ashok";
class StringDemo {
System.out.println(s.charAt(3));//o
public static void main(String[] args) {
System.out.println(s.charAt(100));// RE :
String s="ashoksoft";
StringIndexOutOfBoundsException
System.out.println(s.substring(5));//soft
}
}
}
}
2. public String concat(String str);
6. public String substring(int begin, int end);
Example:
Returns the substring from begin index to end-1 index.
class StringDemo {
Example:
public static void main(String[] args) {
class StringDemo {
String s="ashok";
public static void main(String[] args) {
s=s.concat("software");
String s="ashoksoft";
//s=s+"software";
System.out.println(s.substring(5));//soft
//s+="software";
System.out.println(s.substring(3,7));//okso
System.out.println(s);//ashoksoftware
}
}
}
}
H.O. : B-5,Dev nagar ,opp. Kamal & company ,gopalpura ,Jaipur Tel : 0141-2708941 , Mob : 9887755436, 9413223636 Visit us at : www.fluxeducare.in
CORE JAVA PROGRAMMING
Returns the number of characters present in the string. It returns index of 1st occurrence of the specified
character if the specified
Example:
character is not available then return -1.
class StringDemo {
Example:
public static void main(String[] args) {
class StringDemo {
String s="jobs4times";
public static void main(String[] args) {
System.out.println(s.length());//10
String s="saicharan";
//System.out.println(s.length);//compile time error
System.out.println(s.indexOf('c')); // 3
}
System.out.println(s.indexOf('z')); // -1
}
}
}
8. public String replace(char old, char new);
13. public int lastIndexOf(Char ch);
To replace every old character with a new character.
It returns index of last occurrence of the specified
Example: character if the specified
public static void main(String[] args) { character is not available then return -1.
} String s="arunkumar";
} System.out.println(s.lastIndexOf('a'));//7
Example:
class StringDemo {
System.out.println(s.trim());//sai charan
H.O. : B-5,Dev nagar ,opp. Kamal & company ,gopalpura ,Jaipur Tel : 0141-2708941 , Mob : 9887755436, 9413223636 Visit us at : www.fluxeducare.in
CORE JAVA PROGRAMMING
If the content will change frequently then never Creates an equivalent StringBuffer object for the given
recommended to go for String object because for every String with capacity=s.length()+16;
change a new object will be created internally. To
handle this type of requirement we should go for Example
StringBuffer concept. The main advantage of
StringBuffer over String is, all required changes will be class StringBufferDemo {
performed in the existing object only instead of creating
public static void main(String[] args) {
new object.(won't create new object).
StringBuffer sb=new StringBuffer("ashok");
Constructors
System.out.println(sb.capacity());//21
1. StringBuffer sb=new StringBuffer();
}
Creates an empty StringBuffer object with default
initialcapacity "16". Once StringBuffer object reaches its }
maximum capacity a new StringBuffer object will be
created with
H.O. : B-5,Dev nagar ,opp. Kamal & company ,gopalpura ,Jaipur Tel : 0141-2708941 , Mob : 9887755436, 9413223636 Visit us at : www.fluxeducare.in
CORE JAVA PROGRAMMING
4. public void setCharAt(int index, char ch); 7. public StringBuffer delete(int begin,int end);
To replace the character locating at specified index with To delete characters from begin index to end n-1 index.
the provided character.
8. public StringBuffer deleteCharAt(int index);
Example:
To delete the character locating at specified index.
class StringBufferDemo {
Example:
public static void main(String[] args) {
class StringBufferDemo {
StringBuffer sb=new StringBuffer("ashokkumar");
public static void main(String[] args) {
sb.setCharAt(8,'A');
StringBuffer sb=new StringBuffer("saicharankumar");
System.out.println(sb);
System.out.println(sb);//saicharankumar
}
sb.delete(6,13);
}
System.out.println(sb);//saichar
sb.deleteCharAt(5);
5. public StringBuffer append(String s);
System.out.println(sb);//saichr
class StringBufferDemo {
}
public static void main(String[] args) {
}
StringBuffer sb=new StringBuffer();
9. public StringBuffer reverse();
sb.append("PI value is :");
Example :
sb.append(3.14);
class StringBufferDemo {
sb.append(true);
public static void main(String[] args) {
System.out.println(sb);//PI value is :3.14 true
StringBuffer sb=new StringBuffer("ashokkumar");
}
System.out.println(sb);//ashokkumar
}
System.out.println(sb.reverse());//ramukkohsa
}
6. public StringBuffer insert(int index,String s);
}
Example :
10. public void setLength(int length);
class StringBufferDemo {
Consider only specified no of characters and remove all
public static void main(String[] args) { the remaining characters.
} sb.setLength(6);
} System.out.println(sb);//ashokk
}}
H.O. : B-5,Dev nagar ,opp. Kamal & company ,gopalpura ,Jaipur Tel : 0141-2708941 , Mob : 9887755436, 9413223636 Visit us at : www.fluxeducare.in
CORE JAVA PROGRAMMING
Example:
class StringBufferDemo {
System.out.println(sb.capacity());//1000
sb.append("ashok");
System.out.println(sb.capacity());//1000
sb.trimToSize();
System.out.println(sb.capacity());//5
Example:
class StringBufferExa{
System.out.println(sb.capacity());//default 16
sb.append("Hello");
System.out.println(sb.capacity());//now 16
System.out.println(sb.capacity());
sb.ensureCapacity(10);//now no change
System.out.println(sb.capacity());//now 34
sb.ensureCapacity(50);//now (34*2)+2
System.out.println(sb.capacity());//now 70
H.O. : B-5,Dev nagar ,opp. Kamal & company ,gopalpura ,Jaipur Tel : 0141-2708941 , Mob : 9887755436, 9413223636 Visit us at : www.fluxeducare.in
CORE JAVA PROGRAMMING
Executing several tasks simultaneously is the concept The thread enters the new born state as soon as it is
of multitasking. There are two types of multitasking's. created. The thread is created using the new operator.
From the new born state the thread can go to ready to
1. Process based multitasking. run mode or dead state. If start( ) method is called then
the thread goes to ready to run mode. If the stop( )
2. Thread based multitasking. method is called then the thread goes to dead state.
Process based multitasking:
Executing several tasks simultaneously where each Ready to run mode (Runnable Mode)
task is a separate independent process such type of
multitasking is called process based multitasking. This If the thread is ready for execution but waiting for the
type of multitasking is best suitable at "os level". CPU the thread is said to be in ready to run mode.
All the events that are waiting for the processor are
queued up in the ready to run mode and are served in
Thread based multitasking FIFO manner or priority scheduling. From this state the
thread can go to running state if the processor is
Executing several tasks simultaneously where each
available using the scheduled( ) method.
task is a separate independent part of the same
program, is called Thread based multitasking and each From the running mode the thread can again join the
independent part is called a "Thread". This type of queue of runnable threads. The process of allotting
multitasking is best suitable for "programmatic level". time for the threads is called time slicing.
When compared with "C++", developing multithreading
examples is very easy in java because java provides in Running State
built support for multithreading through a rich API
(Thread, Runnable, ThreadGroup, ThreadLocal...etc). If the thread is in execution then it is said to be in
running state. The thread can finish its work and end
In multithreading on 10% of the work the programmer normally. The thread can also be forced to give up the
is required to do and 90% of the work will be down by control when one of the following conditions arise
java API.
1. A thread can be suspended by suspend( ) method. A
Life cycle of a Thread: suspended thread can be revived by using the resume()
method.
A thread can be in one of the five states. The life cycle of
the thread in java is controlled by JVM. The java thread 2. A thread can be made to sleep for a particular time
states are as follows: by using the sleep(milliseconds) method. The sleeping
method re-enters runnable state when the time elapses.
New
3. A thread can be made to wait until a particular event
Runnable occur using the wait() method, which can be run again
using the notify( ) method.
Running
Blocked State
Non-Runnable (Blocked)
A thread is said to be in blocked state if it prevented
Terminated
from entering into the runnable state and so the
running state. The thread enters the blocked state when
it is suspended, made to sleep or wait. A blocked
thread can enter into runnable state at any time and
can resume execution.
Dead State
H.O. : B-5,Dev nagar ,opp. Kamal & company ,gopalpura ,Jaipur Tel : 0141-2708941 , Mob : 9887755436, 9413223636 Visit us at : www.fluxeducare.in
CORE JAVA PROGRAMMING
We can define a Thread in the following 2 ways. class MyThread extends Thread
{
1. By extending Thread class. public void run()
{ for (int i=0;i<10;i++)
2. By implementing Runnable interface. {
System.out.println("userdefined Thread");
}
}
1. By extending Thread class
}
Step 1: Our normal java class will become Thread class
whenever we are extending predefined Thread class. class ThreadDemo
{
class MyThread extends Thread public static void main(String[] args)
{
{ MyThread t=new MyThread();
t.start();
}; for (int i=0;i<10;i++)
{
Step 2: override the run() method to write the business System.out.println("Main Thread");
logic of the Thread. run() method present in Thread }
class with empty implementations. }
}
class MyThread extends Thread
{
Thread Scheduler
public void run()
If the application contains more than one thread then
{
thread execution decided by thread schedular.
//logics here
Thread scheduler is a part of the JVM. It decides thread
execution. Thread scheduler is a mental patient we are
}
unable to predict exact behavior of Thread Scheduler it
} is JVM vendor dependent.
Step 3: Create userdefined Thread class object. Thread Scheduler fallows two algorithms to decide
Thread execution.
MyThread t=new MyThread();
1) Preemptive algorithm.
Step 4: Start the Thread by using start() method of
Thread class. 2) Time slicing algorithm.
Preemptive scheduling
H.O. : B-5,Dev nagar ,opp. Kamal & company ,gopalpura ,Jaipur Tel : 0141-2708941 , Mob : 9887755436, 9413223636 Visit us at : www.fluxeducare.in
CORE JAVA PROGRAMMING
Difference between t.start() and t.run() methods 2. We can overload run() method but Thread class
start() method always invokes no argument run()
In the case of t.start() a new Thread will be created method the other overload run() methods we have to
which is responsible for the execution of run() method. call explicitly then only it will be executed just like
But in the case of t.run() no new Thread will be created normal method.
and run() method will be executed just like a normal
method by the main Thread. Example
class MyThread extends Thread
{
public void run()
Thread class start() method {
System.out.println("no arg method");
For every Thread the required mandatory activities like
}
registering the Thread with Thread Scheduler will takes
public void run(int i)
care by Thread class start() method and programmer is
{
responsible just to define the job of the Thread inside
System.out.println("int arg method");
run() method. That is start() method acts as best
}
assistant to the programmer.
}
Example: class ThreadDemo
{
start() public static void main(String[] args)
{
{ MyThread t=new MyThread();
t.start();
1. Register Thread with Thread Scheduler }
}
2. All other mandatory low level activities.
Output:
No arg method
3. Invoke or calling run() method.
}
3. If we override start() method then our start() method
We can conclude that without executing Thread class will be executed just like a normal method call and no
start() method there is no chance of starting a new new Thread will be started.
Thread in java. Due to this start() is considered as heart
Example:
of multithreading.
class MyThread extends Thread
Note: {
public void start()
1. If we are not overriding run() method then Thread {
class run() method will be executed which has empty System.out.println("start method");
implementation and hence we won't get any output. }
public void run()
Example: {
class MyThread extends Thread System.out.println("run method");
{} }
class ThreadDemo }
{ class ThreadDemo
public static void main(String[] args) {
{ public static void main(String[] args)
MyThread t=new MyThread(); {
t.start(); MyThread t=new MyThread();
} t.start();
} System.out.println("main method");
It is highly recommended to override run() method. }
Otherwise don't go for multithreading concept. }
Output:
start method
main method
Entire output produced by only main Thread.
Note : It is never recommended to override start()
method.
H.O. : B-5,Dev nagar ,opp. Kamal & company ,gopalpura ,Jaipur Tel : 0141-2708941 , Mob : 9887755436, 9413223636 Visit us at : www.fluxeducare.in
CORE JAVA PROGRAMMING
H.O. : B-5,Dev nagar ,opp. Kamal & company ,gopalpura ,Jaipur Tel : 0141-2708941 , Mob : 9887755436, 9413223636 Visit us at : www.fluxeducare.in
CORE JAVA PROGRAMMING
Every Thread in java having name ,default name of the In java every Thread has some property. It may be
main thread is main & default name of user threads default priority provided be the JVM or customized
starts from Thread-0. priority provided by the programmer. Based on priority
the thread scheduler allocates the cpu.
t1 -->Thread-0 t2 -->Thread-1 t3 -->Thread-2
The valid range of thread priorities is 1 – 10. Where 1 is
To set the name use setName() & to get the name use lowest priority and 10 is highest priority. The default
getName(), priority of main thread is 5 NORM_PRIORITY. The
priority of child thread is inherited from the parent. To
Public final String getName() represent the priority thread class contains three
constants,
Public final void setName(String name)
MIN_PRIORITY = 1
To represent the current thread use currentThread()
method of thread class. NORM_PRIORITY = 5
public static native java.lang.Thread currentThread(); MAX_PRIORITY = 10
To get id of a thread use getId()method. Thread class defines the following methods to get and
set priority of a Thread.
public long getId();
Public final int getPriority()
To check the particular thread is running or not use
isAlive() method. Public final void setPriority(int priority)
public final native boolean isAlive(); Thread priority decide when to switch from one running
thread to another this process is called context
switching. If the more than one thread is having same
class MyThread extends Thread priority then thread execution decide by thread
{ scheduler.
}
class ThreadDemo
{
public static void main(String args[]) class MyThread extends Thread
{ { public void run()
MyThread t1=new MyThread(); {
MyThread t2=new MyThread(); System.out.println("current Thread name
System.out.println("t1 Thread
= "+Thread.currentThread().getName());
name="+t1.getName());
System.out.println("t2 Thread
System.out.println("current Thread
name="+t2.getName()); priority =
System.out.println(Thread.currentThread().get "+Thread.currentThread().getPriority());
Name()); }
t1.setName("flux"); }
t2.setName("bca"); class ThreadDemo
Thread.currentThread().setName(“anil”); {
System.out.println("t1 Thread
public static void main(String[]
name="+t1.getName());
System.out.println("t2 Thread
args)//main thread started
name="+t2.getName()); {
System.out.println(Thread.currentThread().get MyThread t1 = new MyThread();
Name()); MyThread t2 = new MyThread();
System.out.println("t1 Thread id="+t1.getId()); t1.setPriority(Thread.MIN_PRIORITY);
System.out.println("t2 Thread id="+t2.getId()); t2.setPriority(Thread.MAX_PRIORITY);
System.out.println(Thread.currentThread().getI t1.start();
d());
t2.start();
System.out.println("t1 Thread alive or
not="+t1.isAlive());
}
} }
}
H.O. : B-5,Dev nagar ,opp. Kamal & company ,gopalpura ,Jaipur Tel : 0141-2708941 , Mob : 9887755436, 9413223636 Visit us at : www.fluxeducare.in
CORE JAVA PROGRAMMING
Yield() method causes to pause current executing 2. public final void join(long ms) throws
Thread for giving the chance for waiting threads of same InterruptedException
priority. If there are no waiting threads or all threads
are having low priority then the same thread will 3. public final void join(long ms,int ns) throws
continue its execution once again. InterruptedException
H.O. : B-5,Dev nagar ,opp. Kamal & company ,gopalpura ,Jaipur Tel : 0141-2708941 , Mob : 9887755436, 9413223636 Visit us at : www.fluxeducare.in
CORE JAVA PROGRAMMING
H.O. : B-5,Dev nagar ,opp. Kamal & company ,gopalpura ,Jaipur Tel : 0141-2708941 , Mob : 9887755436, 9413223636 Visit us at : www.fluxeducare.in
CORE JAVA PROGRAMMING
Note:
H.O. : B-5,Dev nagar ,opp. Kamal & company ,gopalpura ,Jaipur Tel : 0141-2708941 , Mob : 9887755436, 9413223636 Visit us at : www.fluxeducare.in
CORE JAVA PROGRAMMING
5050
H.O. : B-5,Dev nagar ,opp. Kamal & company ,gopalpura ,Jaipur Tel : 0141-2708941 , Mob : 9887755436, 9413223636 Visit us at : www.fluxeducare.in
CORE JAVA PROGRAMMING
Notify vs notifyAll()
Note:
H.O. : B-5,Dev nagar ,opp. Kamal & company ,gopalpura ,Jaipur Tel : 0141-2708941 , Mob : 9887755436, 9413223636 Visit us at : www.fluxeducare.in
CORE JAVA PROGRAMMING
• In general, execution of an applet does not begin at When an applet begins, the following methods are
main() method. called, in this sequence:
3. paint( )
5. destroy( )
• An applet is a Java class that extends the
java.applet.Applet class.
init
• A main() method is not invoked on an applet, and The init( ) method is the first method to be called. This
an applet class will not define main(). is where you should initialize variables. This method is
called only once during the run time of your applet.
• Applets are designed to be embedded within an
HTML page. Start
• When a user views an HTML page that contains an The start( ) method is called after init( ). It is also called
applet, the code for the applet is downloaded to the to restart an applet after it has been stopped. Note
user's machine. that init( ) is called once i.e. when the first time an
applet is loaded whereas start( ) is called each time an
• A JVM is required to view an applet. The JVM can applet’s HTML document is displayed onscreen. So, if a
be either a plug-in of the Web browser or a separate user leaves a web page and comes back, the applet
runtime environment. resumes execution at start( ).
H.O. : B-5,Dev nagar ,opp. Kamal & company ,gopalpura ,Jaipur Tel : 0141-2708941 , Mob : 9887755436, 9413223636 Visit us at : www.fluxeducare.in
CORE JAVA PROGRAMMING
The paint( ) method is called each time an AWT-based We can get any information from the HTML file as a
applet’s output must be redrawn. This situation can parameter. For this purpose, Applet class provides a
occur for several reasons. For example, the window in method named getParameter(). Syntax:
which the applet is running may be overwritten by
another window and then uncovered. Or the applet public String getParameter(String parameterName)
window may be minimized and then restored. paint( ) is
also called when the applet begins execution. Whatever Example 1:
the cause, whenever the applet must redraw its
output, paint( ) is called. The paint() method is actually
inherited from the java.awt. <html>
<applet code="UseParam.class" width="30
0" height="300">
<param name="msg" value="Welcome to a
These import statements bring the classes into the
pplet">
scope of our applet class
</applet>
</html>
• java.applet.Applet
• java.awt.Graphics
Note:
appletviewer HelloWorld.html
H.O. : B-5,Dev nagar ,opp. Kamal & company ,gopalpura ,Jaipur Tel : 0141-2708941 , Mob : 9887755436, 9413223636 Visit us at : www.fluxeducare.in
CORE JAVA PROGRAMMING
// Drawing lines:
H.O. : B-5,Dev nagar ,opp. Kamal & company ,gopalpura ,Jaipur Tel : 0141-2708941 , Mob : 9887755436, 9413223636 Visit us at : www.fluxeducare.in
CORE JAVA PROGRAMMING
Font getFont()
H.O. : B-5,Dev nagar ,opp. Kamal & company ,gopalpura ,Jaipur Tel : 0141-2708941 , Mob : 9887755436, 9413223636 Visit us at : www.fluxeducare.in
CORE JAVA PROGRAMMING
Example 1: Example 2:
Output:
H.O. : B-5,Dev nagar ,opp. Kamal & company ,gopalpura ,Jaipur Tel : 0141-2708941 , Mob : 9887755436, 9413223636 Visit us at : www.fluxeducare.in
CORE JAVA PROGRAMMING
AWT stands for Abstract Window Tool kit. It is an API to The Panel is the container that doesn't contain title bar
develop GUI, window-based applications in java. and menu bars. It can have other components like
button, textfield etc.
AWT components are platform dependent it displays the
application according to the view of operating system. Frame
AWT is a package it will provide very good predefined
support to design GUI applications. AWT is heavy The Frame is the container that contain title bar and
weight because these components are using operating can have menu bars. It can have other components like
system resources. By using java.awt package we are button, textfield etc.
able to prepare static components to provide the
dynamic nature to the component use java.awt.event
package. It is a sub package of java.awt.
Frame
AWT component Hierarchy
Frame is defined in Java.awt.Frame package. Frame is
a container it contains other components like title bar,
Button, Text Field...etc.
Window
H.O. : B-5,Dev nagar ,opp. Kamal & company ,gopalpura ,Jaipur Tel : 0141-2708941 , Mob : 9887755436, 9413223636 Visit us at : www.fluxeducare.in
CORE JAVA PROGRAMMING
1. By creating object of Frame class To display some textual message on the frame override
paint() method.
Layout Managers
(1) java.awt.FlowLayout
(2) java.awt.BorderLayout
(3) java.awt.GridLayout
(4) java.awt.CardLayout
(5) java.awt.GridBagLayout
H.O. : B-5,Dev nagar ,opp. Kamal & company ,gopalpura ,Jaipur Tel : 0141-2708941 , Mob : 9887755436, 9413223636 Visit us at : www.fluxeducare.in
CORE JAVA PROGRAMMING
1. java.awt.FlowLayout 2. Java.awt.BorderLayout
The FlowLayout is used to arrange the components into The BoderLayout is dividing the frame into five areas
row by row format. Once the first row is filled with north, south ,east, west, center so we can arrange the
components then it is inserted into second row. And it components in these five areas.To represent these five
is the default layout of the applet. The components are areas borderlayout is providing the fallowing 5-constans
arranged in the order as they are added i.e. first
components appears at top left, if the container is not public static final java.lang.String NORTH;
wide enough to display all the components, it is
wrapped around the line. Vertical and horizontal gap public static final java.lang.String SOUTH;
between components can be controlled. The
public static final java.lang.String EAST;
components can be left, center or right aligned.
public static final java.lang.String WEST;
There are 3 types of constructor in the Flow Layout.
They are as following: public static final java.lang.String CENTER
i. FlowLayout()
H.O. : B-5,Dev nagar ,opp. Kamal & company ,gopalpura ,Jaipur Tel : 0141-2708941 , Mob : 9887755436, 9413223636 Visit us at : www.fluxeducare.in
CORE JAVA PROGRAMMING
It arranges all the components in a grid of equally public static final int X_AXIS
sized cells, adding them from the left to right and top
to bottom. Only one component can be placed in a cell public static final int Y_AXIS
and each region of the grid will have the same size.
When the container is resized, all cells are public static final int LINE_AXIS
automatically resized. The order of placing the
public static final int PAGE_AXIS
components in a cell is determined as they were added.
Constructor
Constructor:
BoxLayout(Container c, int axis):
1. GridLayout(): creates a grid layout with one column
per component in a row. creates a box layout that arranges the components with
the given axis.
2. GridLayout(int rows, int columns): creates a grid
layout with the given rows and columns but no
gaps between the components.
6. CardLayout
H.O. : B-5,Dev nagar ,opp. Kamal & company ,gopalpura ,Jaipur Tel : 0141-2708941 , Mob : 9887755436, 9413223636 Visit us at : www.fluxeducare.in
CORE JAVA PROGRAMMING
Button()
AWT controls
Button(String str)
1. Label
methods available in the Button class are as follows:
A label is a GUI control which can be used to display
static text. Label can be created using the Label class void setLabel(String str) – To set or assign the text to be
and its constructors which are listed below: displayed on the button.
Label(String str)
H.O. : B-5,Dev nagar ,opp. Kamal & company ,gopalpura ,Jaipur Tel : 0141-2708941 , Mob : 9887755436, 9413223636 Visit us at : www.fluxeducare.in
CORE JAVA PROGRAMMING
String getSelectedText() – Retrieves the selected text in TextArea(String str, int numLines, int numChars, int
the text field. sBars)
public class MyFrame extends Frame Following are some of the methods available in the
{ TextArea class:
Label myLabel;
String getText() – To retrieve the text in the text area.
TextField tf;
MyFrame() void setText(String str) – To assign or set the text in a
{ text area.
setSize(400, 200);
setTitle("My Application"); String getSelectedText() – To retrieve the selected text in
setLayout(new FlowLayout()); a text area.
myLabel = new Label("Enter name: ");
tf = new TextField(20); void select(int startindex, int endindex) – To select the
add(myLabel); text in text field from startindex to endindex – 1.
add(tf);
} boolean isEditable() – To check whether the text field is
public static void main(String[] args) editable or not.
{
void setEditable(boolean canEdit) – To make a text field
MyFrame mf = new MyFrame();
editable or non-editable.
}
}
void append(String str) – To append the given string to
the text in the text area.
H.O. : B-5,Dev nagar ,opp. Kamal & company ,gopalpura ,Jaipur Tel : 0141-2708941 , Mob : 9887755436, 9413223636 Visit us at : www.fluxeducare.in
CORE JAVA PROGRAMMING
public class MyFrame extends Frame public class MyFrame extends Frame
{ {
TextArea ta; Checkbox c1, c2;
MyFrame() MyFrame()
{ {
setSize(400, 200); setSize(400, 200);
setTitle("My Application"); setTitle("My Application");
setLayout(new FlowLayout()); setLayout(new FlowLayout());
ta = new TextArea(3, 20); setVisible(true);
add(ta); c1 = new Checkbox("Male");
} c2 = new Checkbox("Female");
public static void main(String[] args) add(c1);
{ add(c2);
MyFrame mf = new MyFrame(); }
} public static void main(String[] args)
} {
MyFrame m= new MyFrame();
}
}
6. Radio Button
5. Checkboxes
In AWT, there is no separate class for creating radio
A checkbox control can be created using buttons. The difference between a checkbox and radio
the Checkbox class and its following constructors: button is, a user can select one or more checkboxes.
Whereas, a user can select only one radio button in a
Checkbox() group. Radio buttons can be create by using Checkbox
class CheckBoxGroup class as follows:
Checkbox(String str)
public class MyFrame extends Frame
Checkbox(String str, boolean on)
{
Checkbox(String str, boolean on, CheckboxGroup Checkbox c1, c2;
cbGroup) CheckboxGroup cbg;
MyFrame()
Checkbox(String str, CheckboxGroup cbGroup, boolean {
on) setSize(400, 200);
setTitle("My Application");
Following are various methods available in the setLayout(new FlowLayout());
Checkbox class: setVisible(true);
cbg = new CheckboxGroup();
boolean getState() – To retrieve the state of a checkbox. c1 = new Checkbox("Male", cbg, false);
c2 = new Checkbox("Female", cbg,
void setState(boolean on)– To set the state of a
false);
checkbox.
add(c1);
add(c2);
String getLabel() – To retrieve the text of a checkbox.
H.O. : B-5,Dev nagar ,opp. Kamal & company ,gopalpura ,Jaipur Tel : 0141-2708941 , Mob : 9887755436, 9413223636 Visit us at : www.fluxeducare.in
CORE JAVA PROGRAMMING
A drop down box or a combo box contains a list of items A List box contains a list of items among which the user
(strings). When a user clicks on a drop down box, it can select one or more items. More than one items in
pops up a list of items from which user can select a the list box are visible to the user. A list box can be
single item. created using the List class along with the following
constructors:
A drop down box can be created using the Choice class.
There is only one constructor in the choice class using List()
which we can create an empty list.
List(int numRows)
Following are various methods available in Choice class:
List(int numRows, boolean multipleSelect)
void add(String name) – To add an item to the drop
down list. In the above constructors, numRows specifies the
number of items to be visible to the user and
String getSelectedItem() – To retrieve the item selected by multipleSelect specifies whether the user can select
the user. multiple items or not.
int getSelectedIndex() – To retrieve the index of the item Following are some of the methods available in the List
selected by the user. class:
int getItemCount() – To retrieve the number of items in void add(String name) – To add an item to the list box.
the drop down list.
void add(String name, int index) – To add an item at the
void select(int index) – To select an item based on the specified index in the list box.
given index.
String getSelectedItem() – To get the item name which is
void select(String name) – To select an item based on the selected by the user.
given item name.
int getSelectedIndex() – To get the item index which is
void getItem(int index) – To retrieve an item at the given selected by the user.
index.
String[] getSelectedItems() – To retrieve the selected item
public class MyFrame extends Frame names by the user.
{
Choice myList; int[] getSelectedIndexes() – To retrieve the selected item
MyFrame() indexes by the user.
{
setSize(400, 200); int getItemCount() – To retrieve the number of items in
setTitle("My Application"); the list box.
setLayout(new FlowLayout());
void select(int index) – To select an item based on the
setVisible(true);
given index.
myList = new Choice();
myList.add("CSE"); String getItem(int index) – To retrieve the item at the
myList.add("ECE"); given index.
myList.add("EEE");
myList.add("IT");
add(myList);
}
public static void main(String[] args)
{
MyFrame mf = new MyFrame();
}
}
H.O. : B-5,Dev nagar ,opp. Kamal & company ,gopalpura ,Jaipur Tel : 0141-2708941 , Mob : 9887755436, 9413223636 Visit us at : www.fluxeducare.in
CORE JAVA PROGRAMMING
H.O. : B-5,Dev nagar ,opp. Kamal & company ,gopalpura ,Jaipur Tel : 0141-2708941 , Mob : 9887755436, 9413223636 Visit us at : www.fluxeducare.in