0% found this document useful (0 votes)
6 views89 pages

JAVA Complete Part I

Java is an object-oriented programming language developed by James Gosling in 1991, initially aimed at digital devices. It is known for its portability, simplicity, and security, with key features including being platform-independent and robust. Java supports various programming paradigms, including multi-threading and dynamic loading, and is widely used in application programming across different platforms.

Uploaded by

harin020601
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views89 pages

JAVA Complete Part I

Java is an object-oriented programming language developed by James Gosling in 1991, initially aimed at digital devices. It is known for its portability, simplicity, and security, with key features including being platform-independent and robust. Java supports various programming paradigms, including multi-threading and dynamic loading, and is widely used in application programming across different platforms.

Uploaded by

harin020601
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 89

CORE JAVA PROGRAMMING

HISTROY OF JAVA FEATURES OF JAVA

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

“JAVA” 7. Architecture neutral


Gosling and his team did a brainstorm session and
after the session, they came up with several names 8. High Performance
such as JAVA, DNA, SILK, RUBY, etc.
9. Multithreaded
Java name was decided after much discussion in 1995
10. Distributed
since it was so unique. The name Java originates from a
sort of espresso bean, Java. Gosling came up with this
11. Dynamic
name while having a coffee near his office.
Java was created on the principles like Robust, Simple
Portable, Platform Independent, High Performance,
Multithread, etc. Java is very easy to learn, and its syntax is simple,
clean and easy to understand. According to Sun, Java
Currently, Java is used in internet programming, language is a simple programming language because
mobile devices, games, e-business solutions,
etc. The Java language has experienced a few changes • Java syntax is based on C++.
since JDK 1.0 just as various augmentations of classes • Java has removed many complicated and
and packages to the standard library. In Addition to the rarely-used features like pointers, operator
language changes, considerably more sensational overloading, etc.
changes have been made to the Java Class Library • There is no need to remove unreferenced
throughout the years, which has developed from a objects because there is an Automatic
couple of hundred classes in JDK 1.0 to more than Garbage Collection in Java.
three thousand in J2SE 5.
Platform Independent

Java is platform independent because it is different


from other languages like C, C++, etc. which are
compiled into platform specific machines while Java is
a write once, run anywhere language. A platform is
the hardware or software environment in which a
program runs.

There are two types of platforms software-based and


hardware-based. Java provides a software-based
platform.

The Java platform differs from most other platforms in


the sense that it is a software-based platform that

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

runs on the top of other hardware-based platforms. It Architecture-neutral


has two components:
Java is architecture neutral because there are no
1. Runtime Environment implementation dependent features, for example, the
size of primitive types is fixed.
2. API (Application Programming Interface)
In C programming, int data type occupies 2 bytes of
Java code can be run on multiple platforms, for memory for 32-bit architecture and 4 bytes of memory
example, Windows, Linux, Sun Solaris, Mac/OS, etc. for 64-bit architecture. However, it occupies 4 bytes of
Java code is compiled by the compiler and converted memory for both 32 and 64-bit architectures in Java.
into bytecode. This bytecode is a platform-independent
code because it can be run on multiple platforms, i.e.,
Write Once and Run Anywhere (WORA).
Portable
Secured
Java is portable because it facilitates you to carry the
Java is best known for its security. With Java, we can Java bytecode to any platform. It doesn't require any
develop virus-free systems. Java is secured because: implementation.

• 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

Robust A thread is like a separate program, executing


concurrently. We can write Java programs that deal
Robust simply means strong. Java is robust because: with many tasks at once by defining multiple threads.
The main advantage of multi-threading is that it
• It uses strong memory management. doesn't occupy memory for each thread. It shares a
• There is a lack of pointers that avoids security common memory area. Threads are important for
problems. multi-media, Web applications, etc.
• There is automatic garbage collection in java
which runs on the Java Virtual Machine to get Dynamic
rid of objects which are not being used by a
Java application anymore. Java is a dynamic language. It supports dynamic
• There are exception handling and the type loading of classes. It means classes are loaded on
checking mechanism in Java. All these points demand. It also supports functions from its native
make Java robust. languages, i.e., C and C++.

Java supports dynamic compilation and automatic


memory management (garbage collection).

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.

• In encapsulation, the variables or data of a


class is hidden from any other class and can
1. Object be accessed only through any member
function of own class in which they are
It is a basic unit of Object Oriented Programming and declared.
represents the real life entities. A typical Java program • As in encapsulation, the data in a class is
creates many objects. An object consists of hidden from other classes, so it is also known
as data-hiding.
State: It is represented by attributes of an object. It also
• Encapsulation can be achieved by Declaring
reflects the properties of an object.
all the variables in the class as private and
Behavior: It is represented by methods of an object. It writing public methods in the class to set and
also reflects the response of an object with other get the values of variables.
objects.

Identity: It gives a unique name to an object and


enables one object to interact with other objects.

Example: student, car etc.

2. Class

A class is a user defined blueprint or prototype from Access Specifiers


which objects are created. It represents the set of
properties or behaviors that are common to all objects Access specifiers decide the scope of a data member,
of one type. Properties are represented as variables that method or class. There are four types of access
hold some values and behaviors are represented as specifiers in java:
methods (similar to functions in other programming
languages). public: Accessible to all. Other objects can also access
this member variable or function.

private: Not accessible by other objects. Private


members can be accessed only by the methods in the
same class. Object accessible only in class in which
they are declared.

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.

• The parent class is called the base class or


super class. The child class that extends the base
class is called the derived class or sub class or child
class.

Types of Inheritance

Single Inheritance: It refers to a child and parent


class relationship where a class extends another
class.

Multilevel inheritance: It refers to a child and parent


Polymorphism in Java is of two types:
class relationship where a class extends the child
1. Run time polymorphism class. For example, class A extends class B and class
B extends class C.
2. Compile time polymorphism
Hierarchical inheritance: It refers to a child and
parent class relationship where more than one classes
extends the same class. For example, class B extends
Run time polymorphism class A and class C extends class A.

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.

Compile time polymorphism

In Java, compile time polymorphism refers to a process


in which a call to an overloaded method is resolved at
compile time rather than at run time. Method
overloading is an example of compile time
polymorphism. Method Overloading is a feature that
allows a class to have two or more methods having the
same name but the arguments passed to the methods
are different. Unlike method overriding, arguments can
differ in:

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:

Comparison C++ Java


Index

Platform- C++ is platform-dependent. Java is platform-independent.


independent

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.

Hardware C++ is nearer to hardware. Java is not so interactive with hardware.

Object-oriented C++ is an object-oriented language. Java is also an object-oriented language.


However, in C language, single root However, everything (except fundamental
hierarchy is not possible. types) is an object in Java. It is a single root
hierarchy as everything gets derived from
java.lang.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

Java Tokens 3) Int

Smallest individual part of a java program is called java 4) Long


token. A token is the smallest element of a program that
is meaningful to the compiler. Tokens define the b) Floating point data types
structure of the java language. It is possible to allow
any number of spaces between two tokens. 1) Float

Java tokens can be divided into following categories: 2) Double

1. Identifiers 2. Char datatype (For represent character)

2. Keywords 3. Boolean datatype (For represent logical values)

3. Literals

4. Operators 1. byte

5. Separators Size= 8 bits or 1 byte

Java Identifiers Range= -128 to 127

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.

Rules for declare Identifier: • Positive numbers represented directly in the


memory whereas negative numbers represented in
1. An identifier contains group of uppercase (A-Z) and 2’s complement form. e.g.
lowercase (a-z) characters, numbers (0-9),
underscore(_) and dollar sign ($) characters but not byte b= 100;
start with number.
byte b= 127;
2. Java identifiers are case sensitive.
byte b= 130; (compile time error)
3. The identifier should not duplicate.
byte b= true; (compile time error)
4. It is possible to declare all predefined class names
• This datatype is most suitable if we want to handle
and interfaces as identifiers but it is not
data in terms of streams either form the file or form
recommended to use.
the network.
5. It is not possible to use keywords as a identifiers.
2. short
6. There is no length limit for identifiers but is never
Size= 2 bytes
recommended to take lengthy names because it
reduces readability of the code.
Range= -215 to 215-1 [-32768 to 32767]

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)

Primitive Data type • Most rarely used datatype in Java is “short”

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

3. int Boolean Data Type

Size= 4 bytes Size:- Not Applicable (virtual machine dependent)

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

Range = -263 to 263 -1

Floating Point Data Type

Float Double Integral Literals

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. If we want 5 to 6 3. If we want to 14 to Allowed digits are 0 to 9


decimal place of 15 decimal place of
accuracy we should accuracy we should e.g. int x=10;
go for float. go for double.
2. Octal literals
4. Float follows single 4. Double follows
precision. double precision. Allowed digits are 0 to 7

Literal value should be prefixed with “0”.

e.g. int x=010;

3. Hexadecimal Literals

• Allowed digits are 0 to 9, a to f or A to F

• 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)

Example: double d=0123.456;(valid) //it is treated as decimal


value but not octal
1. int x=0777; //(valid)
double d=0x123.456;//(invalid)
2. int x=0786; //(invalid)
• We can assign integral literal directly to the floating
3. int x=0xFACE; (valid) point data types and that integral literal can be
specified in decimal , octal and Hexa decimal form
4. int x=0xbeef; (valid) also.

5. int x=0xBeer; //(invalid) double d=0xBeef;

6. int x=0xabb2cd; //(valid) • we can't assign floating point literal directly to the
integral types

e.g. int i= 123.456;


NOTE
• We can specify floating point literal even in
By default, every integral literals I s of int type but we
scientific form also [exponential form]
can specify explicitly as long type by suffixing with l or
L.
double d=10e2
1) int i = 10;

2) int i = 10l; (compile time error)


Boolean Literals
3) long i= 10l;
The only possible values for the Boolean data types are
true/false.
4) long i= 10;
1. boolean b=true;(valid)
• There is no way to specify integral literals is of byte
and short type explicitly. 2. boolean b=0;//C.E:incompatible types(invalid)

• 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.

e.g. char ch= ‘a’;

Floating point literals char ch = a; (compile time error)

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.

We can specify floating point literal explicitly as double Example


type by suffixing with d or D.

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. Char ch= 97;

s.o.p(ch); a

2. char ch= 65535;

s.o.p(ch);

• A char literal can be represented in Unicode


representation which is nothing but “\uxxxx” 4-
digit hexadecimal number.

1. char ch= ‘\u0061’; S.o.p (ch) ; a

2. char ch= ‘\uabcd’;

3. char ch= ‘\UFace’;

4. char ch= ‘\i beaf’;

• Every escape character is a char literal

1. Char ch= ‘\n’;

2 char ch= ‘\t’;

3 char ch= ‘\t’;

Escape character Meaning

\n New line

\t Horizontal tab

\r Carriage return

\b Back space

\f Form feed

\’ Single quads

\” Double quads

\\ Back slach

String Literals

Any sequence of characters with in double quotes (“ ”)


is called string literal.

e.g. string s = “java”;

The following promotions will be performed


automatically by the compiler.

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

short if public try class new void enu goto true


m

byte else private catch interface instanceof const false

int switch protected throw extends super null

long case static throws implements this

float default final finally package

double while abstract assert import

char do synchronized

boolean for native

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

Command Line Arguments Example 2

The arguments which are passing from Command Within the main(), commandline arguments are
prompt are called Command Line arguments. available in string form.

The main objective of Command Line arguments are we Class Test


can customize the behavior of the main()
{
Ex- java test x y z
p.s.v.m (String[]args)
Args [0]
{
Args [1]
s.o.p(args[0]+args[1]);
Args [2]
}
Args.length=3
}

Space in the separator between command line


Note arguments, if the command line arguments itself
contain space then we should enclose within (“ ”)
1. In java command line argument is by default String.
2. If we have n number of argums then args[0] to Example 3
args[n-1]
3. When we can pass parameter with the help of class Test
command line then it is separated by space.
4. If we declare more than one arguments then we {
must pass same number of arguments in command
p.s.v.m (String[] args)
prompt, else compiler gives an error.
{

s.o.p(args[0]); Note book

}
Example 1
}
Class Test
Java Test “Note Book”
{

p.s.v.m(string[] args)

for (int i=0; i<=args.length; i++)

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

• Increment\ Decrement -5%-12=-5

• Arithmetic Operator In modulus operator output sign is depends on the


numerator not denominator.
• Concatenation

• 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

• Short-circuit (i) simple : x=10,x=y

• Instanceof variable declaration and initialization is performed


simultaneously.
• Typecast operator
(ii) chained: x=y=z=10
• Assignment operator
First declare all the variable then assign
• Conditional operator simultaneously.

• New operator (iii)compound (other+assignment)

• [] operator += -+ %= *= /=

&= |= ^= >>= >>>= <<=

In compound assignment operators, the required type


casting will be performed automatically by the compiler.
1. Arithmetic operator
Example 1
There are following operator available for arithmetic
operator

+,-,*,/,%

• Whenever we are performing any arithmetic


operation between two variables a & b the result
type is always:

output=max (int, type of a, type of b)


Example 2
byte+ byte = int
byte+ short = int int a, b, c, d;
int + long = long
long + float = float a=b=c=d=20;
double + char= double
a+=b*=c+=d/=2;
char + char = int
s.o.p(a+”………”+b+”…….……”+c+”………..”+d);
Exception is generated only for the integral division
operations. 620 600 30 10

If one of the numbers is floating type then output is


infinity or -infinity

If both are zero and of the floating type then outpt is


NaN (not a number)

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

3. Increment/Decrement (Unary operator) 4. String concatenation

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

int x=10; s.o.p (d+a+b+c); flux102030

y=++x x=11 y=11 (first increment and then assign) s.o.p (a+d+b+c); 10flux2030

y=x++ x=11 y=10 (first assign and then increment)


If at least one operand is string type then ‘+’ operator
acts as concatenation, otherwise acts as arithmetic
 We can apply increment and decrement only for operator.
variables but not for constant values.

++4 (compile time error)


5. Relational operator
 Nesting of increment and decrement operators are
not allowed otherwise we will get compile time error. Relational operator are >, <, <=, >=

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

6. Equality Operators 8. Bitwise operator

Equality operators are ==, != Bitwise operators are &, | and ^.

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.

2. ‘a’ ==’b’ S.o.pln(T&T) ; T

3. true == false S.o.pln(T|T) ; T

4. 10.5 == 12.3 S.o.pln(T^T) ; F

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

Bitwise compilement operator (~)

7. instanceof operator we can apply bitwise complement operator only for


integral types but not for Boolean type.
By using this operator, we can check, whether the given
object is of a particular type or not. Example

Syntax: (1) S.o.p(~True);

r instanceof x C.E: operator ~ can’t be applied to Boolean.

where r is any reference and x is class/interface. (2) S.o.p(~4); -5

Example

Short x=10; NOTE:

Integer a=20; - The most significant bit represents sign bit. 0


means +ve number , 1 means -ve number.
boolean y,z;
- +ve number will be represent directly in the
y=x instanceof Short; memory , where as –ve numbers will be
represented in 2’s component form.
z=a instanceof Integer;
Boolean component operator (!)
System.out.println(y+" "+z);
We can apply these operators only for Boolean
type, not for integral types.

Example

(1) S.o.p(!4);

CE: operator! cant be applied to it.

(2) S.o.p(! false); True

(3) S.o.p(! true); false

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

9. Logical operator 10. Conditional operator

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

&,| && , || int x=(a>b) ?40:50;

Both operands should 2nd operand evaluation is a>b is true then 40


be evaluated always. optional.
a>b is false then 50
Relatively low Relatively high
performance. performance. S.o.pln(x):50

Applicable for both Applicable only for


Boolean and integral Boolean types.
types. Nesting of conditional operator is possible.

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:

S.o.pln(x+ ……….. +y);


12. [] operator
Output:
We can use these operator for declaring or creating
array.
x y
13. Type cast operators
& 11 17
There are 2 types of primitive type castings
| 12 16
1. Implicit type
|| 12 15
2. Explicit type
&& 11 17
Implicit type casting

1.Compiler is the responsible to perform this type


casting.

2. this type casting is required whenever we are


assigning smaller data type value to bigger data type.

3. it is also known as “Widening or upcasting”.

4. no loss of information in this type casting.

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 1. unary operators

1. Double d=10; S.o.pln(d); 10.0 [],x++,x--,++x,--x,~,!,new,<type> (used to type cast)

(compiler converts to double automatically) 2. arithmetic operators

2. int x= ‘a’ ; S.o.pln(x);97 *, %, +, -, /

(complier converts c har to int automatically) 3. shift operator:

Explicit type casting >>>, <<, >>

1. Programmer is responsible to perform this type 4. comparison operator:


casting.
<, <=, >, >=, instance of
2. It is required whenever we are assigning bigger data
type value to the smaller data type variable. 5. equity operator:

3. It is aka “narrowing or down casting ”. ==,!=

4. There may be chance of loss of information in this 6. bitwise operator


type casting.
&, ^, |
- The following are various possible conversions
where explicit type casting is required. 7. short circuit operator

Example &&,||

1. byte b=126; 8. conditional operator

C.E.: possible loss of precision ?:

Found: int 9. assignment operator

Required: byte =,+=,-=,…..

2.byte b =(byte)130;

S.o.p(b); -126

Whenever we are assigning bigger data type value to the


smaller data type variable the the most significant bit
will be loosed.

whenever we are assigning floating point data type


value to the integral data types by explicit type casting
the digits after the decimal points will be loosed.

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

CONTROL STATEMENTS 2. switch statement

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;

1. Selection statements case 2: action 2 ;

1. if condition: If we want to execute only one ,


statement which is based on condition then go for if
condition. ,

If condition have following types: default : default action ;

i. simple if }

ii if else Note:

iii Nested if else (i) curly braces are mandatory

iv Ladder else if (ii) Both case and default are optional inside a switch

Syntax: (iii) Within the switch , every statement should be under


some case or default , independent statement are not
if (b) allowed .

{ (iv)Allowed datatypes for switch argument are byte,


short, int and char if we are passing any other type we
action if b is true
will get compile time error.
}
(v) Every case label should be within the range of
else switch argument type otherwise we will get compile time
error.
{
(vi) Every case label should be a valid compile time
action if b is true constant , if we are taking variable as case label we will
get compile time error .
}
(vii) Duplicate case labels are not allowed.
Note:

(i) The argument to the if statements should be boolean


type. if we are providing any other type, we will get
compile time error. default case

(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

ARRAY Array construction


Every array in java is an object hence we can create by
An array is an indexed collection of fixed number of using new operator
Example:
homogeneous data elements. The main advantage of
int[] a=new int[3];
arrays is we can represent multiple values with the
same name so that readability of the code will be
improved.

But the main disadvantage of arrays is Fixed in size Note:


that is once we created an array there is no chance of • At the time of array creation compulsory, we should
increasing or decreasing the size based on our specify the size otherwise we will get compile time
error.
requirement that is to use arrays concept compulsory.
int[] a=new int[3];
we should know the size in advance which may not int[] a=new int[];//C.E:array dimension missing
possible always.
• It is legal to have an array with size zero in java.
ARRAY DECLARATIONS • If we are taking array size with -ve int value then we
will get runtime exception.
One dimensional array • The allowed data types to specify array size are byte,
short, char, int. By mistake if we are using any other
type we will get compile time error.
int[ ] a
• The maximum allowed array size in java is maximum
value of int size [2147483647].
int [ ]a;

int a[ ]; Multi-dimensional array


In java multidimensional arrays are implemented as
Note: array of arrays approach but not matrix form.
The main advantage of this approach is to improve
memory utilization.
At the time of declaration, we can't specify the size
otherwise we will get compile time error. Example

Two dimensional array int[][] a=new int[2][];


a[0]=new int[3];
int[][] a; a[1]=new int[2];
int [][]a;
int a[][];
int[] []a;
int[] a[];
int []a[];

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

Whenever we are creating an array every element is


initialized with default value automatically.

int[] a=new int[3];


System.out.println(a);

We can perform declaration, construction


and initialization of an array in a single
line.

We can extend this short cut even for multi dimensional


arrays also.

int[][] a={{10,20,30},{40,50}};

int[][][]
a={{{10,20,30},{40,50}},{{60},{70,80},{90
,100,110}}};

length

1. It is the final variable applicable only for arrays.

2. It represents the size of the array.

Example:

int[] x=new int[3];


System.out.println(x.length);//3

int[][] a=new int[6][3];


System.out.println(a.length);//6
System.out.println(a[0].length);//3

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 types of value represented by a variable, Example


all variables are divided into 2 types
Class Test
(i) Primitive variables
{
(ii) Reference variables
int x=10;

public static void main(String[] args)


Primitive variables
{
It can be used to represent primitive values.
System. out. println(x);
Example: int x=10;
Test t=new Test();
Reference variables
System. Out. Println(t.x);
It can be used to refer Objects.
}
Example: Student s=new Student ();
Public void main()

{
Based on the purpose and position of declaration all
variables are divided into 3 types: System. Out. Println(x);

(i) Instance variables }

(ii) Static variables }

(iii) Local variables

For the instance variables it is not required to perform


initialization explicitly, Jvm will provide default values.
Instance variables
Example:
If the value of the variable is varied from the object to
object such type of variables is called instance Class Test
variables.
{
For every object a separate copy of instance variable will
created. String s;

The scope of instance variables is exactly same as the Int x;


scope of the objects because Instance variables will be
Boolean b;
created at the time of object creation and destroy at the
time of object destruction. Public static void main(String[] args)

Instance variables will be stored as the part of objects. {

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()

Static variables can be accessed either by using class {


name or by using object reference, but recemented to
use class name. System. Out. Println(x);

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”.

If we performing any change in instance variable these


changes wanted to be reflected for the remaining
objects. Because, for every object a separated copy of
instance variables will be them.

But, if we performing any change to the static variable,


these changes will be reflected for all objects because
we are maintaining a single copy.

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: NOTE:

To meet temporary requirements of the programmers o It is not recommended to perform initialization of


sometimes we have to create variables inside method or local variables inside logical blocks because there is
constructor. Such types of variables are called Local no guarantee execution of these blocks at runtime.
variables.
o It is highly recommended to perform initialization for
Local variables also known as Stock variables or the local variables at the time of declaration, at least
Automatic variables or temporary variables. with default values.

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

Public static void main(String[] args)

Int x;

If(args.length>0)

x=10;

Else

X=20;

System. Out. Println(x);

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

JAVA METHODS There are two types of methods in java,

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

Method Syntax: Inside the class it is possible to declare n number of


instance & static methods based on the developer
[modifiers-list] return-Type Method-name (parameters requirement. It will improve the reusability of the code
list) throws Exception and we can optimize the code.

Method name ---> functionality name

Parameter-list ---> input to functionality Instance 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

Method Signature: //instance area

Method-name & parameters list is called method }


signature.
Instance member’s memory is allocated during object
Syntax: creation hence accesses the instance members by using
object-name (reference-variable).
Method-name(parameter-list)
Objectname.instancemethod();//calling

Test t = new Test();


Every method contains three parts:
t.m1( );
1. Method declaration

2. Method implementation (logic)


Static method:
3. Method calling
If you apply static keyword with any method, it is
void m1() ------> method declaration known as static method.
{
• A static method belongs to the class rather than the
object of a class.
Body (Business logic); -----> method implementation
• A static method can be invoked without the need for
} creating an instance of a class.
• A static method can access static data member and
Test t = new Test(); can change the value of it.

t.m1(); ------> method calling

There are two main restrictions for the static method.


They are:

• The static method cannot use non static data


member or call non-static method directly.
• this and super cannot be used in static context.

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.

If the method expecting three arguments must pass


three arguments, not less than three not more than
static void m1() three.

{ Method arguments are always local variables.

//static area

} class Test

Static member’s memory allocated during .class file {


loading hence access the static members by using
class-name. void m1(int a, char ch) //local variables

Classname.staticmethod( ); // call static method {

Test.m2( ); System.out.println("m1 instance method");

System.out.println(a);

instance & static methods without arguments: System.out.println(ch);

class Test static void m2(String str,boolean b,double d)

{ {

void m1() System.out.println("m2 static method");

{ System.out.println(str);

System.out.println("m1 instance method"); System.out.println(b);

} System.out.println(d);

static void m2() }

{ void m3(int a, int b)

System.out.println("m2 static method"); {

} System.out.println(“m3 method”);

public static void main(String[] args) System.out.println(a);

{ System.out.println(b);

Test t = new Test(); }

t.m1(); public static void main(String[] args)

Test.m2(); {

} Test t = new Test();

} 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

int y=200; public static void main(String[] args)

t.m3(x,y); {

} Test t = new Test();

} int x = t.m1();

System.out.println("m1 method return value="+x);

methods vs return type. boolean b = Test.m2();

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);

If the method is having return type other than void then }


must return the value by using return keyword
}
otherwise compiler will generate error message “missing
return statement

Inside the method it is possible to declare only one


return statement, that statement must be last
statement of the method otherwise compiler will It is possible to print return value of the method in two
generate error message. ways,

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

Passing objects in java Call by Value and Call by Reference in Java

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){

While creating a variable of a class type, we only create data=data+100;


a reference to an object. Thus, when we pass this
reference to a method, the parameter that receives it }
will refer to the same object as that referred to by the
argument. public static void main(String args[])

This effectively means that objects act as if they are {


passed to methods by use of call-by-reference. Changes
to the object inside the method do reflect in the object Operation op=new Operation();
used as an argument.
System.out.println("before change "+op.data);

op.change(500);

System.out.println("after change "+op.data);

Call by reference Example:

class Operation2

int data=50;

void change(Operation2 op)

op.data=op.data+100;

public static void main(String args[])

Operation2 op=new Operation2();

System.out.println("before change "+op.data);

op.change(op);//passing object

System.out.println("after change "+op.data);

} }

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 keyword: to invoke current class method

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);
}
}
}
}

this keyword is used for following:

• this can be used to refer current class instance


variable.
• this can be used to invoke current class method
(implicitly)
• this() can be used to invoke current class
constructor.
• this can be passed as an argument in the method
call.
• this can be passed as argument in the constructor
call.
• this can be used to return the current class
instance from the 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

to pass as an argument in the method

this keyword can also be passed as an argument in the


method. It is mainly used in the event handling.

class S2

void m(S2 obj)

System.out.println("method is invoked");

void p()

m(this);

public static void main(String args[]){

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();

In Java, a constructor is a block of codes similar to the }


method. It is called when an instance of the class is
created. At the time of calling constructor, memory for }
the object is allocated in the memory. It is a special type
of method which is used to initialize the object. Every In above application when we create object by using
time an object is created using the new() keyword, at new keyword “Test t = new Test()” then compiler is
least one constructor is called. searching for “Test()” constructor inside the class since
not available hence compiler generate default
It is called constructor because it constructs the values constructor at the time of compilation.
at the time of object creation. It is not necessary to write
a constructor for a class. It is because java compiler
creates a default constructor if our class doesn't have
Note:
any.
Only the compiler generated 0-argument constructor is
Rules to declare constructor
called default constructor. The user defined 0-argument
(1) Constructor name class name must be same. constructor is not a default constructor

(2) It is possible to provide parameters to constructors.

(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"); }

} public static void main(String[] args)

public static void main(String[] args) {

{ Test t1=new Test();

Test t = new Test(); Test t2=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

t1.m1(); One method is able to call more than one method at a


time but one constructor is able to call only one
t2.m1(); constructor at time.

Test()

Note: {

Inside the class if we are declaring at least one this(10);


constructor (either 0-arg or parameterized) then
compiler not generating default constructor. this(10,20);

class Test System.out.println("0-arg cons");

{ }

Test(int i) error: call to this must be first statement in constructor

System.out.println("1-arg constructor"); Advantages of constructors:

}  Constructors are used to write the logics these logics


are executed during object creation.
public static void main(String[] args)
 Constructors are used to initialize the values to
{ instance variables during object creation.

Test t1=new Test(); //error : inside the class no 0-arg  Constructor is a special method used to initialize the
constructor object.

Test t2=new Test(10);

If we are trying to compile above code the compiler will


generate error message “Cannot find symbol ” because
compiler is unable to generate default constructor.

Constructor calling:

To call Current class constructor use this keyword

this(); ----> current class 0-arg constructor calling

this(10); ----> current class 1-arg constructor calling

Inside the constructor this keyword must be first


statement.

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

Static blocks will be executed at the time of class


loading hence if we want to perform any activity at the
time of class loading we have to define that activity
inside static block. With in a class we can take any no.
Of static blocks and all these static blocks will be
executed from top to bottom.

Read indirectly write only state (or) RIWO :

With in the static block if we are trying to read any


variable then that read is considered as "direct read".

If we are calling a method , and within the method if we


are trying to read a method , that read is called Indirect
read If a variable is in RIWO state then we can't perform
read operation directly otherwise we will get compile
time error saying " illegal forward reference ".

Output:

First static block

Second static block

JAVA Means DURGA SIR

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 Test Static blocks are used to initialize static variables.

{ 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"); }

} public static void main(String[] args)

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

INSTANCE BLOCK Output:

Instance blocks are used to write the logics of projects 0


& these logics are executed during object creation just first instance block
before constructor execution. second instance block
constructor
Syntax main method

{
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:

During compilation the compiler will copy instance


blocks code in every constructor. The constructor logics Note:
are specific to object but instance block logics are
common for all objects. static control flow is one time activity and it will be
executed at the time of class loading. But instance
control flow is not one time activity for every object
creation it will be executed

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

Instance blocks are used to initialize instance variables


during object creation.

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();
}
}

When we declare instance block & instance variable the


execution order is top to bottom.

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

POLYMORPHISM method overloading with type promotion

One functionality with different behaviors is called


polymorphism. The ability to appear in more forms is
called polymorphism. Polymorphism is the ability of an
object to take on many forms Polymorphism is derived
from 2 greek words: poly and morphs. The word "poly" Type promotion means implicit type casting it perform
means many and "morphs" means forms. So from left to right.
polymorphism means many forms.
class Test
There are two types of polymorphism in java,
{
(1) Compile time polymorphism / static binding / early
binding void m1(int a,long b)

(2) Runtime polymorphism /dynamic binding /late {


binding.
System.out.println("int,long arguments method");

}
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);

a. Same method name but different number of t.m1((byte)10,(short)20);


arguments.
t.m1('a','b'); // here the Unicode values are assigned
void m1(int a){}
t.m1(10.5f);
void m1(int a,int b){}
t.m1(10);
b. Same method name & same number of arguments
t.m1('a');
but different data types.
t.m1((byte)10);
void m1(int a){}
}
void m1(char ch){}
}
To achieve overloading concept one java class sufficient.
It is possible to overload any number of methods in
single java class.

Note:

While overloading the methods check the


signature(methodname+parameters) of the method but
not return type.

To the overloaded methods it is possible to declare any


return type.

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 Overloading Operator overloading

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.

Test(int i)  If at least one operand is String then “+” perform


concatenation.
{

System.out.println("int argument constructor");


Example
}
class Test
Test(char ch,int i)
{
{
public static void main(String[] args)
System.out.println("char,int argument constructor");
{
}
int a=10,b=20;;
Test(char ch)
System.out.println(a+b);
{
System.out.println(“flux”+"educare");
System.out.println("char argument constructor");
}
}
}
public static void main(String[] args)

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

The process of acquiring properties (variables) &


methods (behaviors) from one class to another class is
called inheritance.

We are achieving inheritance concept by using extends


keyword. Also known as is-a relationship. Extends
keyword is providing relationship between two classes.
The main objective of inheritance is code extensibility
whenever we are extending the class automatically code
is reused.
Hybrid is combination of multiple & hierarchical, java
not supporting hybrid.

In java if we are extending the class then it will be


parent class, if we are not extending the class then
Example:
object class will become the default super class.
class Parent
• The root class of all java classes is “object” class.
• Every java class contains parent class except object {
class.
• In java every class is child class of object either public void methodOne(){ }
directly (A) or indirectly (B,C).
• Object class present in java.lang package and it }
contains 11 methods & all java classes able to use
class Child extends Parent
these 11 methods because Object class is root class
of all java classes. {
• To check the predefined support use javap
command. public void methodTwo() { }

Javap full-class-name }

Types of inheritance

There are five types of inheritance in java,

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: METHOD OVERRIDING

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.

FINAL KEYWORD Example:

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 }

If we make any class as final, we cannot extend it.


Rules for overriding:

(1) Overridden method signature & overriding method


signatures must be same.

(2) The return types of overridden method & overriding


method must be same (at primitive level).

(3) While overriding it is possible to change return type


by using co-variant return types concept.

(4) Final methods can’t override.

(5) Static method can’t override but method hiding


possible.

(6) Private methods can’t override.

(7) Overriding it is possible to maintain same


permission or increasing order but not decreasing.

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.

class Parent  Co-variant return type: The return type of overriding


method is must be sub-type of overridden method
{ return type this is called covariant return types.

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);
}
}

super class methods calling


class Parent
{
void m1()
{
System.out.println("parent m1() method");}
}
class Child extends Parent
{
void m1()
{
System.out.println("child class m1() method");}
void m3()
{
this.m1(); // this is optional
super.m1();
}
public static void main(String[] args)
{
new Child().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

super class constructors calling

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,

}  Two super keywords are not allowed.

}  Two this keywords are not allowed.

class Child extends Parent  Both super & this keyword also not allowed.

{ Case 4:

Child() In below example parent class default constructor is


executed that is provided by compiler.
{
class Parent
this(10); //current class 1-arg constructor calling
{
System.out.println("Child 0-arg constructor");
// default constructor
}
}
Child(int a)
class Child extends Parent
{
{
super(); //super class 0-arg constructor calling
Child()
System.out.println("child 1-arg constructor--->"+a);
{
}
super()
public static void main(String[] args)
System.out.println("Child 0-arg constructor");
{
}
new Child();
public static void main(String[] args)
}
{
}
new Child();

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 5: Super class instance blocks

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

Dynamic Method Dispatch (Runtime Polymorphism) ref = b;

Method overriding is one of the ways in which Java ref.m1();


supports Runtime Polymorphism. Dynamic method
dispatch is the mechanism by which a call to an ref = c;
overridden method is resolved at run time, rather than ref.m1();
compile time. }
}
When an overridden method is called through a
superclass reference, Java determines which
version(superclass/subclasses) of that method is to be Advantages of Dynamic Method Dispatch
executed based upon the type of the object being
referred to at the time the call occurs. Thus, this
• Dynamic method dispatch allows Java to support
determination is made at run time.
overriding of methods which is central for run-time
polymorphism.
At run-time, it depends on the type of the object being
referred to (not the type of the reference variable) that • It allows a class to specify methods that will be
common to all of its derivatives, while allowing
determines which version of an overridden method will
subclasses to define the specific implementation of
be executed. A superclass reference variable can refer to
some or all of those methods.
a subclass object. This is also known as upcasting.
Java uses this fact to resolve calls to overridden • It also allow subclasses to add its specific methods
methods at run time. subclasses to define the specific implementation of
some.
class A
{
void m1()
{
System.out.println("Inside A's m1 method");
}
}

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

ABSTRACT CLASS Example1:

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.

Every abstract method must end with semicolon. Example 2:

To represent method is abstract use abstract modifier. class Parent

Example: {

abstract void m1 (); ---->method declaration public abstract void methodOne(){}

If a class contain at least on abstract method then }


compulsory the corresponding class should be declare
Output:
with abstract modifier. Because implementation is not
complete and hence, we can't create object of that class. Compile time error.

Even though class doesn't contain any abstract


methods still we can declare the class as abstract that
is an abstract class can contain zero no of abstract
methods also.
Example 3:
To represent particular class is abstract class use
abstract modifier. class Parent

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}

abstract void m3();

Case 2:

Abstract class does not contain abstract methods.

abstract class Test

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

If the abstract class contains abstract methods write


the implementation in child classes. If the child class is
unable to provide implementation of all abstract class abstract class Test2 extends Test1
methods then declare the child class with abstract
modifier and complete the remaining method {
implementations in next created child classes.
void m2(){System.out.println("m2 method");}
It is possible to declare multiple child classes but at
}
final complete the implementation of all abstract
methods. If we are completing implementations of all class Test3 extends Test2
methods then only it is possible to create the object and
access the methods. {

Example 1: void m3(){System.out.println("m3 method");}

abstract class Parent public static void main(String[] args)

{ {

public abstract void methodOne(); Test3 t = new Test3();

public abstract void methodTwo(); t.m1();

} t.m2();

class child extends Parent t.m3();

{ t.m4();

public void methodOne(){} }

} }

Output:

Compile time error. Inside the abstract class it is possible to declare the
constructor.

abstract class Test


Example 2: {
Test()
abstract class Test
{
{ System.out.println("abstrac calss con");
}
abstract void m1(); }

abstract void m2(); class Test1 extends Test


{
abstract void m3(); Test1()
{
void m4(){System.out.println("m4 method");} super();
System.out.println("normal class con");
}
}
abstract class Test1 extends Test public static void main(String[] args)
{
{ new Test1();
}
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

INTERFACE Different between interface and class

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:

Interface interface-name Note:

{ 1. While providing implementation of interface methods


that implementation methods must be public because
//abstract methods here; interface methods are by default public & abstract.
Otherwise, compiler generate error message “attempting
} to assign weaker access privileges”.

2. The interface is able to hold the implementation class


object.
Before compilation
interface It1 Interface-name reference-variable = new class-name();
{
void m1(); Example
void m2();
void m3(); interface it
}
{

After compilation void m1();


abstract interface It1
{ void m2();
public abstract void m1();
public abstract void m2(); void m3();
public abstract void m3();
} }

Class Test implements it


Note:
{
The interfaces are by default abstract so interfaces
public void m1()
object creation not allowed & interface methods are by
default public and abstract.
{

System.out.println(“m1-method implementation ”);


Use of Interface
}
1. It is used to achieve fully abstraction.
Public void m2()
2. By using Interface, you can achieve multiple
{
inheritance in java.
System.out.println(“m2-method implementation”);

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 void m3() abstract class Test1 extends Test

{ {

System.out.println(“m3 –method implementation”); public void m2(){System.out.println("m2 method");}

} }

Public static void main(String[] args) class Test2 extends Test1

{ {

Test t=new Test(); public void m3(){System.out.println("m3 method");

t.m1(); }

t.m2(); public static void main(String[] args)

t.m3(); {

It i =new Test(); Test2 t = new Test2();

i.m1(); t.m1(); t.m2(); t.m3();

i.m2(); }

i.m3(); }

} Important points

• One class is able to extends only one class at a time


but one interface is able to extends more than one
Interface contains abstract methods write the interface at a time.
implementation in implementation class. If the • If the more than one interface contains same
implementation class is unable to provide the method then override that method only once.
implementation of all abstract methods then declare
implementation class with abstract modifier & complete
the remaining abstract method implementation in next
created child classes. In java it is possible to take any
number of child classes but at final complete the
implementation of all abstract methods.

Example:

interface It

void m1();

void m2();

void m3();

abstract class Test implements It

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

Interface variables: Example 2: (variables vs ambiguity)

Inside the interface it is possible to declare variables interface It1


these variables are by default public static final. {
int a=10;
Inside the interface it is not possible to declare the }
instance variables. interface It2
{
Inside the interface it is not possible to declare int a=100;
constructors, instance blocks, static blocks. }
class Test implements It1,It2
Example 1:
{
interface It1 public void m1()
{
{ //System.out.println(a); error: reference to a is
ambiguous
int a=10; System.out.println(It1.a);
System.out.println(It2.a);
void m1(); }
public static void main(String[] args)
}
{
Test t = new Test();
class Test implements It1
t.m1();
{ }
}
public void m1()

System.out.println("m1 method");

a=a+10;

System.out.println(a);

public static void main(String[] args)

Test t = new Test();

t.m1();

Output: cannot assign a value to final variable a

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

PACKAGE Example 1: (valid)

In java the predefined support maintained in the form package com.flux;


of packages and these packages contains classes &
interfaces, & enum & Annotations and these all are import java.io.*;
contains predefined methods & variables & constants.
import java.lang.*;
java-language java

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.

Java.lang java.beans java.text java.sql package flux;

Java.io java.net java.nio java.math class Test

Java.util java.applet java.rmi {

Java.awt java.times java.security public static void main(String[] args)

Types of packages System.out.println("package first example");

There are two types of packages in java }

1) Predefined packages. }

2) User defined packages. class A

Predefined packages: {

The predefined packages contains predefined classes & }


interfaces and these class & interfaces contains
predefined variables and methods. interface It

Example:- java.lang, java.io ,java.util…..etc {

User defined 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.

syntax : javac ---> java compiler

package package-name; -d ---> creates folder structure

Note: . ---> current working directory

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

Step-4:-execution process. Whenever we are importing a package all classes and


interfaces present in that package are by default
Execute the .class file by using fully qualified name available but not sub package classes.
(class name with complete package structure).

java flux.Test

Whenever we are using other packages classes then


must import that package by using import statement.
There are two ways to import the classes Complete Example:
1) Explicit class import

2) Implicit class import package flux.educare;

public class Mca


{
Explicit class import:
public int x,y;
public Mca(int x,int y)
This type of import is highly recommended to use
{
because it improves readability of the code.
this.x=x;
Example: import java.util.ArrayList; this.y=y;
}

public void show()


Implicit class import: {
System.out.println("x="+x+" "+"y="+y);
It is never recommended to use because it reduces }
readability of the code. }

Example: import java.util.*;

package flux.educare;

public class Bca extends Mca


{
public int z;
public Bca(int x,int y,int z)
Whenever we are using fully qualified name it is not {
required to use import statement. Similarly whenever super(x,y);
we are using import statements it is not require to use this.z=z;
fully qualified name. }

Example: public void Add()


{
class MyArrayList extends java.util.ArrayList System.out.println("x="+x+" y="+y+" z="+z);
System.out.println("Add="+(x+y+z));
{
}
}
}

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

EXCEPTION HANDLING Unchecked Exception

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.

2. Rest of the application is not executed.

To overcome above limitation in order to execute the class Test


rest of the application & to get normal termination of
{ public static void main(String[] args)
the application must handle the exception.
{
There are two ways to handle the exceptions in java.
System.out.println(10/0);
1) By using try-catch block
java.lang.ArithmeticException: / by zero
2) By using throws keyword
int[] a={10,20,30};

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

Note: try-catch block

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
}

Without try catch

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

Note: Try with multiple catch blocks:

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.

2. If any statement which raises an exception and it is


not part of any try block then it is always abnormal
try
termination of the program.
{
3. There may be a chance of raising an exception inside .
catch and finally blocksalso in addition to try block .
.
.
}
Various methods to print exception information: catch(FileNotFoundException e)
{
Throwable class defines the following methods to print use local file
exception information to the console. }
catch(ArithmeticException e)
printStackTrace():
{
This method prints exception information in the perform these Arithmetic operations
following format. }
catch(SQLException e)
Name of the exception: description of exception Stack {
trace don't use oracle db, use mysqldb
}
toString(): catch(Exception e)
{
This method prints exception information in the default handler
following format. }

Name of the exception: description of exception

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

class Test It is not recommended to take clean up code inside try


{ block because there is no guarantee for the execution of
public static void main(String[] args) every statement inside a try.
{
try It is not recommended to place clean up code inside
{ catch block because if there is no exception then catch
System.out.println(10/0); block won't be executed.
}
catch(Exception e) We require some place to maintain clean up code which
{ should be executed always irrespective of whether
e.printStackTrace(); exception raised or not raised and whether handled or
} not handled. Such type of best place is nothing but
catch(ArithmeticException e) finally block. Hence the main objective of finally block is
{ to maintain cleanup code.
e.printStackTrace();
}}}
CE:exception try
java.lang.ArithmeticException has {
already been caught risky code
}
catch(x e)
{
handling code
class Test }
{ finally
public static void {
main(String[] args) cleanup code
{ }
try
{ Case-1: If there is no Exception:
System.out.println(10/0);
}
catch(ArithmeticException e) class Test
{ {
e.printStackTrace(); public static void main(String[] args)
} {
catch(Exception e) try
{ {
e.printStackTrace(); System.out.println("try block executed");
}}} }
Output: catch(ArithmeticException e)
Compile successfully. {
System.out.println("catch block
executed");
}
finally
{
System.out.println("finally block
executed");
}
}
}
Output:
try block executed
Finally block executed

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-2: If an exception raised but the corresponding Throw statement


catch block matched:
In general, we can use throw keyword for customized
exceptions but not for predefined exceptions.
Sometimes we can create Exception object explicitly and
class Test
we can hand over to the JVM manually by using throw
{
keyword.
public static void main(String[] args)
{
try
{
System.out.println("try block executed");
System.out.println(10/0);
}
catch(ArithmeticException e)
{
The result of following 2 programs is exactly same.
System.out.println("catch block
executed");
}
finally class Test
{ {
System.out.println("finally block public static void main(String[] args){
executed"); System.out.println(10/0);
} }}
} In this case creation of ArithmeticException
} object and handover to the jvm will be
Output: performed automatically by the main()
Try block executed method.
Catch block executed
Finally block executed

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

class Test Throws statement


{
public static void main(String[] args) In our program if there is any chance of raising checked
{ exception then compulsory, we should handle either by
throw new ArithmeticException("/ by try catch or by throws keyword otherwise the code won't
zero"); compile. By using throws it is possible to handle
System.out.println("hello"); multiple exceptions because one method is able to
} throws multiple exceptions at time. We can write the
} throws keyword at method declaration level. We can
Output: provide the throws keyword only at method &
Compile time error. constructor level but not block level.
Test3.java:5: unreachable statement
System.out.println("hello");
Hence the main objective of "throws" keyword is to
delegate the responsibility of exception handling to the
caller method.

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.

throws" keyword required only to convince complier.


Usage of throws keyword doesn't prevent abnormal
class Test3 extends RuntimeException termination of the program. Hence recommended to use
try-catch over throws keyword.
{
Example:
public static void main(String[] args){
class Test
throw new Test3();
{
public static void main(String[] args){
}
Thread.sleep(5000);
} }
}
Output: We can handle this compile time error by using the
following 2 ways.
Runtime error: Exception in thread

"main" Test3 at Test3.main(Test3.java:4)

By using try catch

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

By using throws keyword Customized Exceptions

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();
}
}

In above example exception raised in studentDetails()


method but it delegating responsibilities of exception
handling to hod() method by using throws keyword. But
hod() method delegating responsibilities of exception
handling to principal() method by using throws now
principal handing this exception by using try-catch
blocks.

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

Java String literal is created by using double quotes.


For Example:

String s="flux";

Each time you create a string literal, the JVM checks


the "string constant pool" first. If the string already
exists in the pool, a reference to the pooled instance is
returned. If the string doesn't exist in the pool, a new
string instance is created and placed in the pool. For
example: String class constructors :

String s1="flux"; 1. String s=new String();

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.

String s=new String("flux"); Example:

//creates two objects and one reference variable class StringDemo {

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

5. String s=new String(byte[] b); 3. public boolean equals(Object o);

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.

class StringDemo { 4. public boolean equalsIgnoreCase(String s);

public static void main(String[] args) { For content comparison where case is not important.

byte[] b={100,101,102}; Example:

String s=new String(b); class StringDemo {

System.out.println(s);//def public static void main(String[] args) {

}} String s="java";

System.out.println(s.equals("JAVA"));//false

Important methods of String class: System.out.println(s.equalsIgnoreCase("JAVA"));//true

1. public char charAt(int index); }

Returns the character locating at specified index. }

Example: 5. public String substring(int begin);

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

7. public int length(); 12. public int indexOf(char ch)

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

class StringDemo { Example:

public static void main(String[] args) { character is not available then return -1.

String s="ababab"; class StringDemo {

System.out.println(s.replace('a','b'));//bbbbbb public static void main(String[] args) {

} String s="arunkumar";

} System.out.println(s.lastIndexOf('a'));//7

9. public String toLowerCase(); System.out.println(s.indexOf('z'));//-1

Converts the all characters of the string to lowercase. }

10. 20. public String toUpperCase(); }

Converts the all characters of the string to uppercase.

11. public String trim();

We can use this method to remove blank spaces present


at beginning and end of the string but not blank spaces
present at middle of the String.

Example:

class StringDemo {

public static void main(String[] args) {

String s=" sai charan ";

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

StringBuffer 3. StringBuffer sb=new StringBuffer(String s);

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

Newcapacity=(currentcapacity+1)*2. Important methods of StringBuffer

Example 1. public int length();

class StringBufferDemo { Return the no of characters present in the StringBuffer.

public static void main(String[] args) { 2. public int capacity();

StringBuffer sb=new StringBuffer(); Returns the total no of characters StringBuffer can


accommodate(hold).
System.out.println(sb.capacity());//16
3. public char charAt(int index);
sb.append("abcdefghijklmnop");
It returns the character located at specified index.
System.out.println(sb.capacity());//16
Example:
sb.append("q");
class StringBufferDemo {
System.out.println(sb.capacity());//34
public static void main(String[] args) {
}
StringBuffer sb=new
} StringBuffer("saiashokkumarreddy");

2. StringBuffer sb=new StringBuffer(int initialcapacity); System.out.println(sb.length());//18

Creates an empty StringBuffer object with the specified System.out.println(sb.capacity());//34


initial capacity.
System.out.println(sb.charAt(14));//e
Example:
System.out.println(sb.charAt(30));//RE :
class StringBufferDemo {
StringIndexOutofBoundsException
public static void main(String[] args) {
}
StringBuffer sb=new StringBuffer(19);
}
System.out.println(sb.capacity());//19

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.

StringBuffer sb=new StringBuffer("abcdefgh"); Example:

sb.insert(2, "xyz"); class StringBufferDemo {

sb.insert(11,"9"); public static void main(String[] args) {

System.out.println(sb);//abxyzcdefgh9 StringBuffer sb=new StringBuffer("ashokkumar");

} 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

11. public void trimToSize(); }

To deallocate the extra allocated free memory such that


capacity and size are equal.

Example:

class StringBufferDemo {

public static void main(String[] args) {

StringBuffer sb=new StringBuffer(1000);

System.out.println(sb.capacity());//1000

sb.append("ashok");

System.out.println(sb.capacity());//1000

sb.trimToSize();

System.out.println(sb.capacity());//5

12. public void ensureCapacity(int initialcapacity);

The ensureCapacity() method of StringBuffer class


ensures that the given capacity is the minimum to the
current capacity. If it is greater than the current
capacity, it increases the capacity by (oldcapacity*2)+2.
For example if your current capacity is 16, it will be
(16*2)+2=34.

Example:

class StringBufferExa{

public static void main(String args[]){

StringBuffer sb=new StringBuffer();

System.out.println(sb.capacity());//default 16

sb.append("Hello");

System.out.println(sb.capacity());//now 16

sb.append("java is my favourite language");

System.out.println(sb.capacity());

//now (16*2)+2=34 i.e (oldcapacity*2)+2

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

MULTITHREADING New Born State

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

The running thread ends its life when it has completed


executing the run() method which is called natural
dead. The thread can also be killed at any stage by
using the stop( ) 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 ways to define a new Thread

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.

t.start(); We can’t expect exact behavior of the thread scheduler


it is JVM vendor dependent. So we can’t say expect
output of the multithreaded examples we can say the
possible outputs.

Preemptive scheduling

In this highest priority task is executed first after this


task enters into waiting state or dead state then only
another higher priority task come to existence.

Time Slicing Scheduling

A task is executed predefined slice of time and then


return pool of ready tasks. The scheduler determines
which task is executed based on the priority and other
factors.

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

Defining a Thread by implementing Runnable


interface:
class MyThread implements Runnable
{
We can define a Thread even by implementing Runnable
public void run()
interface also. Runnable interface present in java.lang {
package and contains only one method run(). for (int i=0;i<10;i++)
{
System.out.println("userdefined Thread");
}
}
};
class ThreadDemo
{
public static void main(String[] args)
{
MyThread r=new MyThread();
Thread t=new Thread(r);
t.start();
for (int i=0;i<10;i++)
{ System.out.println("Main Thread");
}
}
};

Step 1: Our normal java class will become Thread class


whenever we are implementing Runnable interface.
Sleep method
class MyRunnable implements Runnable
sleep() method is a static method used to stop the
{ thread particular amount of time. This method throws
interrupted exception and it is a checked exception
} hence handle the checked exception by using try-catch
blocks or throws keyword.
Step2: override run method to write logic of Thread.
public static native void sleep(long) throws
class MyClass extends Runnable java.lang.InterruptedException;
{
public void run() public static void sleep(long, int) throws
{ java.lang.InterruptedException;
}
} Example:
Step 3: Creating a object.
class MyThread extends Thread
MyClass obj=new MyClass(); {
public void run()
Step 4: Pass object of MyClass in Thread class {
constructor for (int i=0;i<10;i++)
{
Thread t=new Thread(obj);
System.out.println("Thread is running.......");
try {
Step 5: start the thread by using Thread class start
Thread.sleep(1000);
method.
}
t.start(); catch(InterruptedException ie)
{
}
}
}
public static void main(String[] args)
{
MyThread t = new MyThread();
t.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

Thread name & id & isAlive Thread Priorities

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

Java.lang.Thread.yield() 1. public final void join()throws InterruptedException

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

Public static native void yield();

Every join() method throws InterruptedException, which


is checked exception hence compulsory we should
class MyThread extends Thread handle either by try catch or by throws keyword
{ otherwise we will get compile time error.
public void run()
{
for(int i=0;i<10;i++)
class MyThread extends Thread
{
{
Thread.yield(); public void run()
System.out.println("child thread"); {
} for(int i=0;i<5;i++)
} {
} System.out.println("Sita Thread");
class ThreadYieldDemo try
{ {
Thread.sleep(2000);
public static void main(String[] args)
}
{ catch (InterruptedException e){}
MyThread t1=new MyThread(); }
t1.start(); }
for(int i=0;i<10;i++) }
{ class ThreadJoinDemo
System.out.println("main thread"); {
} public static void main(String[] args)throws
InterruptedException
}
{
} MyThread t=new MyThread();
t.start();
//t.join(); //--->1
for(int i=0;i<5;i++)
{
System.out.println("Rama Thread");
}
}
Join Method

If a Thread wants to wait until completing some other


Thread then we should go for join() method. If we are commenting line 1 then both Threads will be
executed simultaneously and we can't expect exact
Example: If a Thread t1 executes t2.join() then t1 execution order.
should go for waiting state until completing t2.
If we are not commenting line 1 then main Thread will
wait until completing child Thread in this the output is
sita Thread 5 times followed by Rama Thread 5 times.

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

Waiting of child Thread untill completing main Thread Synchronization

1. Synchronized is the keyword applicable for methods


and blocks but not for classes and variables.
class MyThread extends Thread
{
2. If a method or block declared as the synchronized
static Thread mt;
public void run()
then at a time only one Thread is allow to execute that
{ method or block on the given object.
try
{ 3. The main advantage of synchronized keyword is we
mt.join(); can resolve date inconsistency problems.
}
catch (InterruptedException e){} 4. But the main disadvantage of synchronized keyword
for(int i=0;i<5;i++) is it increases waiting time of the Thread and effects
{ performance of the system.
System.out.println("Child Thread");
} 5. Hence if there is no specific requirement then never
}
recommended to use synchronized keyword.
}
6. Internally synchronization concept is implemented by
class ThreadJoinDemo
using lock concept.
{
public static void main(String[] args)throws
InterruptedException
7. Every object in java has a unique lock. Whenever we
{ are using synchronized keyword then only lock concept
MyThread mt=Thread.currentThread(); will come into the picture.
MyThread t=new MyThread();
t.start(); 8. If a Thread wants to execute any synchronized
for(int i=0;i<5;i++) method on the given object 1st it has to get the lock of
{ that object. Once a Thread got the lock of that object
Thread.sleep(2000); then it's allow to execute any synchronized method on
System.out.println("Main Thread");
that object. If the synchronized method execution
}
completes then automatically Thread releases lock.
}
}
9. While a Thread executing any synchronized method
the remaining Threads are not allowed execute any
synchronized method on that object simultaneously.
But remaining Threads are allowed to execute any non-
synchronized method simultaneously. [lock concept is
implemented based on object but not based on 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 level lock:

class Display 1. Every class in java has a unique lock. If a Thread


{
wants to execute a static synchronized method then it
public synchronized void wish(String name)
{
required class level lock.
for(int i=0;i<5;i++)
{ 2. Once a Thread got class level lock then it is allow to
System.out.print("good morning:"); execute any static synchronized method of that class.
try
{ 3. While a Thread executing any static synchronized
Thread.sleep(1000); method the remaining Threads are not allow to execute
} any static synchronized method of that class
catch (InterruptedException e) simultaneously.
{}
System.out.println(name); 4. But remaining Threads are allowed to execute normal
}
synchronized methods, normal static methods, and
}
normal instance methods simultaneously.
}
class MyThread extends Thread
5. Class level lock and object lock both are different and
{
Display d; there is no relationship between these two.
String name;
MyThread(Display d,String name)
{
this.d=d; Synchronized block:
this.name=name;
} 1. If very few lines of the code required synchronization
public void run() then it's never recommended to declare entire method
{ as synchronized we have to enclose those few lines of
d.wish(name); the code with in synchronized block.
}
} 2. The main advantage of synchronized block over
class SynchronizedDemo
synchronized method is it reduces waiting time of
{
Thread and improves performance of the system.
public static void main(String[] args)
{
Display d1=new Display();
MyThread t1=new MyThread(d1,"dhoni");
MyThread t2=new MyThread(d1,"yuvaraj");
t1.start();
t2.start();
}
}

If we are not declaring wish() method as synchronized


then both Threads will be executed simultaneously and
we will get irregular output.

If we declare wish()method as synchronized then the


Threads will be executed one by one that is until
completing the 1st Thread the 2nd Thread will wait in
this case we will get regular output.

Note:

If multiple threads are operating on multiple objects


then there is no impact of Syncronization. If multiple
threads are operating on same java objects then
syncronized concept is required(applicable).

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

INTER THREAD COMMUNICATION

Two Threads can communicate with each other by class ThreadA


{
using wait(), notify() and notifyAll() methods. The Thread
public static void main(String[] args)throws
which is required updation it has to call wait() method InterruptedException
on the required object then immediately the Thread will {
entered into waiting state. The Thread which is ThreadB b=new ThreadB();
performing updation of object, it is responsible to give b.start();
notification by calling notify() method. After getting synchronized(b)
notification the waiting Thread will get those updations. {
System.out.println("main Thread calling wait()
wait(), notify() and notifyAll() methods are available in method");//step-1
b.wait();
Object class but not in Thread class because Thread
System.out.println("main Thread got
can call these methods on any common object.
notification call");//step-4
System.out.println(b.total);
To call wait(), notify() and notifyAll() methods
}
compulsory the current Thread should be owner of that }
object i.e., current Thread should has lock of that object }
i.e., current Thread should be in synchronized area. class ThreadB extends Thread
Hence we can call wait(), notify() and notifyAll() methods {
only from synchronized area otherwise we will get int total=0;
runtime exception saying IllegalMonitorStateException. public void run()
{
synchronized(this)
Once a Thread calls wait() method on the given object
{
1st it releases the lock of that object immediately and
System.out.println("child thread starts
entered into waiting state. Once a Thread calls notify() calcuation");//step-2
(or) notifyAll() methods it releases the lock of that object for(int i=0;i<=100;i++)
but may not immediately. Except these {
(wait(),notify(),notifyAll()) methods there is no other total=total+i;
place(method) where the lock release will be happen. }
System.out.println("child thread giving
notification call");//step-3
this.notify();
Once a Thread calls wait(), notify(), notifyAll() methods }
on any object then it releases the lock of that particular }
}
object but not all locks it has.

1. public final void wait()throws InterruptedException

2. public final native void wait(long ms)throws


InterruptedException
Output:
3. public final void wait(long ms,int ns)throws
InterruptedException main Thread calling wait() method

child thread starts calculation


4. public final native void notify()
child thread giving notification call
5. public final void notifyAll()
main Thread got notification call

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()

We can use notify() method to give notification for only


one Thread. If multiple Threads are waiting then only
one Thread will get the chance and remaining Threads
has to wait for further notification. But which Thread
will be notify(inform) we can't expect exactly it depends
on JVM.

We can use notifyAll() method to give the notification for


all waiting Threads. All waiting Threads will be notified
and will be executed one by one, because they are
required lock

Note:

On which object we are calling wait(), notify() and


notifyAll() methods that corresponding object lock we
have to get but not other object locks.

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

APPLET Life cycle of an Applet

An applet is a Java program that can be embedded into


a web page. It runs inside the web browser and works
at client side. An applet is embedded in an HTML page
using the APPLET or OBJECT tag and hosted on a web
server.

• All applets are sub-classes (either directly or


indirectly) of java.applet.Applet class.

• Applets are not stand-alone programs. Instead, they


run within either a web browser or an applet
viewer. JDK provides a standard applet viewer tool
called applet viewer.

• In general, execution of an applet does not begin at When an applet begins, the following methods are
main() method. called, in this sequence:

• Output of an applet window is not performed 1. init( )


by System.out.println(). Rather it is handled with
various AWT methods, such as drawString(). 2. start( )

3. paint( )

Differences between an applet and a simple program 4. stop( )

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( ).

• The JVM on the user's machine creates an instance Stop


of the applet class and invokes various methods
during the applet's lifetime. The stop( ) method is called when a web browser leaves
the HTML document containing the applet—when it
• Applets have strict security rules that are enforced goes to another page, for example. When stop() is
by the Web browser. The security of an applet is called, the applet is probably running. we should
often referred to as sandbox security, comparing use stop( ) to suspend threads that don’t need to run
the applet to a child playing in a sandbox with when the applet is not visible. You can restart them
various rules that must be followed. when start( ) is called if the user returns to the page.

• Other classes that the applet needs can be


downloaded in a single Java Archive (JAR) file.
destroy

The destroy( ) method is called when the environment


determines that our applet needs to be removed
completely from memory. At this point, we should free
up any resources the applet may be using. The
stop( ) method is always called before destroy( ).

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

Paint Parameter passing in Applet

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

Without those import statements, the Java compiler


would not recognize the classes Applet and Graphics,
which the applet class refers to. import java.applet.Applet;
import java.awt.Graphics;

public class UseParam extends Applet


{
import java.applet.Applet;
public void paint(Graphics g)
import java.awt.Graphics;
{
String str=getParameter("msg");
/*
g.drawString(str,50, 50);
<applet code="HelloWorld" width=200
}
height=60>
</applet>
*/

public class HelloWorld extends Applet


{
public void paint(Graphics g)
{
g.drawString("Hello java”, 20, 20);
}

Note:

To execute HelloWorld with an applet viewer, we may


also execute the HTML file shown earlier. For example,
if the preceding HTML file is saved with
HelloWorld.html, then the following command line will
run HelloWorld :

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

Example 2: Graphics in java

The java.awt.Graphics is an abstract class, as the


actual act of drawing is system-dependent and device-
import java.awt.*;
dependent. Each operating platform will provide a
import java.applet.*;
/*<applet code="Paramdemo.class" width="500" subclass of Graphics to perform the actual drawing
height="500"> under the platform, but conform to the specification
<param name="name" value="Flux"> defined in Graphics.
<param name="num1" value="10">
<param name="num2" value="20">
</applet>*/
public class Paramdemo extends Applet
{
String msg="";
String str="";
int a,b; Graphics Class' Drawing Methods
public void init()
{ We are probably used to Cartesian coordinates,
msg=getParameter("name");
where x and y values can be positive or negative. In
a=Integer.parseInt(getParameter("num1"));
b=Integer.parseInt(getParameter("num2"));
contrast, Java uses a coordinate system where the
} origin is in the upper-left corner. That way, x and y are
always positive integers.
public void paint(Graphics g)
{
if(msg==null)
str="welcome";
else
str="welcome " +msg;
g.drawString(str,100,200);
g.drawString("add="+(a+b),150,300);
}
}

Fig: Difference between Cartesian coordinates and Java


graphical coordinates.

Graphical coordinates are measured in pixels; each


pixel corresponds to a dot on the screen.
The Graphics class provides methods for drawing three
types of graphical objects:

1. Text strings: via the drawString() method. Take


note that System.out.println() prints to the system
console, not to the graphics screen.

2. Vector-graphic primitives and shapes: via


methods drawXxx() and fillXxx(), where Xxx could
be Line, Rect, Oval, Arc, PolyLine, RoundRect,
or 3DRect.

3. Bitmap images: via the drawImage() method.

1. Drawing (printing) texts on the graphics screen:

drawString(String str, int xBaselineLeft, int yBaselineLeft);

// Drawing lines:

drawLine(int x1, int y1, int x2, int y2);

drawPolyline(int[] xPoints, int[] yPoints, int numPoint);

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

Graphics Class' Methods for Maintaining the


Graphics Context
// Drawing primitive shapes:
The graphic context maintains states (or attributes)
drawRect(int xTopLeft, int yTopLeft, int width, int such as the current painting color, the current font for
height); drawing text strings, and the current painting
rectangular area (called clip). You can use the
drawOval(int xTopLeft, int yTopLeft, int width, int methods getColor(), setColor(), getFont(), setFont(), getCl
height); ipBounds(), setClip() to get or set the color, font, and
clip area. Any painting outside the clip area is ignored.
drawArc(int xTopLeft, int yTopLeft, int width, int height,
int startAngle, int arcAngle); // Graphics context's current color.
draw3DRect(int xTopLeft, int, yTopLeft, int width, int void setColor(Color c)
height, boolean raised);
Color getColor()
drawRoundRect(int xTopLeft, int yTopLeft, int width, int
height, int arcWidth, int arcHeight) // Graphics context's current font.

drawPolygon(int[] xPoints, int[] yPoints, int numPoint); void setFont(Font f)

Font getFont()

// Filling primitive shapes: To choose the color of a shape, invoke setColor on


the Graphics object:
fillRect(int xTopLeft, int yTopLeft, int width, int height);

fillOval(int xTopLeft, int yTopLeft, int width, int height); g.setColor(Color.red);


The setColor method determines the color of everything
fillArc(int xTopLeft, int yTopLeft, int width, int height, that gets drawn afterward. Color.red is a constant
int startAngle, int arcAngle); provided by the Color class; to use it you have
to import java.awt.Color. Other colors include:
fill3DRect(int xTopLeft, int, yTopLeft, int width, int
height, boolean raised);
black blue cyan darkGray gray green
lightGray magenta orange pink white yellow
fillRoundRect(int xTopLeft, int yTopLeft, int width, int
height, int arcWidth, int arcHeight)

fillPolygon(int[] xPoints, int[] yPoints, int numPoint);

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:

import java.awt.*; import java.awt.*;


import java.applet.*; import java.applet.*;
/*<applet code="Helloapplet.class", /* <applet code="Smile.class" width="500"
height="500", width="500"> height="500">
</applet>*/ </applet> */
public class Helloapplet extends Applet
{ public class Smile extends Applet
public void paint(Graphics g) {
{ public void paint(Graphics g)
g.setColor(Color.RED); {
g.drawLine(50,50,50,400); g.setColor(Color.RED);
g.drawRect(250,350,100,200); g.drawOval(40,40,120,150);
g.fillRect(150,250,100,100); g.drawOval(57,75,30,20);
g.drawRoundRect(300,50,100,150,30,20); g.drawOval(110,75,30,20);
g.setColor(Color.BLUE); g.fillOval(68,81,10,10);
g.drawOval(400,500,200,150); g.fillOval(121,81,10,10);
g.fillOval(500,600,200,150); g.drawOval(85,100,30,30);
g.drawString("part1",720,100); g.fillArc(60,125,80,40,180,180);
g.fillArc(700,100,200,300,0,90); g.drawOval(25,92,15,30);
g.setColor(Color.GREEN); g.drawOval(160,92,15,30);
g.fillArc(700,100,200,300,0,-90); }
g.setColor(Color.PINK); }
g.fillArc(700,100,200,300,90,60);
g.setColor(Color.BLACK);
g.fillArc(700,100,200,300,150,120);
Output:
}
}

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

JAVA AWT Panel

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.

When we create a Frame class object. Frame will be


created automatically with invisible mode, so to provide
the visible nature to the frame use setVisible() method
of Frame class which have following syntax

public void setVisible(boolean b)

where b=true visible mode b=false invisible mode.

When we created a frame, the frame is created with


initial size 0 pixel heights & 0 pixel width hence it is not
visible. To provide particular size to the Frame use
setSize() method which have following syntax

public void setSize(int width,int height)

To provide title to the frame use following method

public void setTitle(String Title)


Component When we create a frame, the default background color
of the Frame is white. If we want to provide particular
The root class of java.awt package is Component class.
color to the Frame we have to use the following method.
Container
public void setBackground(color c)
The Container is a component in AWT that can contain
other components like buttons, textfields, labels etc.
The classes that extends Container class are known as There are two approaches to create Frame in java
container such as Frame, Dialog and Panel.
1. By creating object of Frame class.

2. By extending the Frame class.

Window

The window is the container that have no borders and


menu bars. We must use frame, dialog or another
window for creating a 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

Displaying text on the screen

1. By creating object of Frame class To display some textual message on the frame override
paint() method.

public void paint(Graphics g)


import java.awt.*;
class Demo To set a particular font to the text use Font class
{ present in java.awt package
public static void main(String[] args)
{ Font f=new Font(String type,int style,int size);
Frame f=new Frame();
f.setVisible(true); Font f= new Font("arial",Font.Bold,30);
f.setSize(400,400);
f.setBackground(Color.red);
f.setTitle("myframe"); import java.awt.*;
} class MyFrame extends Frame
} {
MyFrame()
2. By extending the Frame class
{
setVisible(true);
setSize(500,500);
import java.awt.*; setTitle("myframe");
class MyFrame extends Frame setBackground(Color.red);
{ }
MyFrame() public static void main(String[] args)
{ { MyFrame t = new MyFrame();
setVisible(true); }
setSize(500,500); public void paint(Graphics g)
setTitle("myframe"); {
setBackground(Color.green); Font f=new Font("arial",Font.ITALIC,25);
} g.setFont(f);
public static void main(String[] args) g.drawString("hello java",100,100);
{ }
MyFrame f=new MyFrame(); }
}
}

Layout Managers

When we are trying to add the components into


container without using layout manager the
components are overriding hence the last added
component is visible on the container instead of all. To
overcome above problem to arrange the components
into container in specific manner use layout manager.

The layout managers are used to arrange the


components in a Frame in particular manner. Or

A layout manager is an object that controls the size and


the position of components in a container. Different
layouts in java is as follows:

(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()

ii. FlowLayout(int align)

iii. FlowLayout(int align, int hgap, int vgap)


import java.awt.*;
class MyFrame extends Frame
import java.awt.*; {
class MyFrame extends Frame Button b1,b2,b3,b4,b5;
{ MyFrame()
Button b1,b2,b3,b4,b5; {
MyFrame() this.setSize(400,400);
{ this.setVisible(true);
this.setSize(400,400); this.setTitle("BorderLayout");
this.setVisible(true); this.setLayout(new BorderLayout());
this.setTitle("BorderLayout"); b1=new Button("Boys");
this.setLayout(new FlowLayout(FlowLayout.RIGHT)); b2=new Button("Girls");
b1=new Button("Boys"); b3=new Button("management");
b2=new Button("Girls"); b4=new Button("Teaching Staff");
b3=new Button("management"); b5=new Button("non-teaching staff");
b4=new Button("Teaching Staff"); this.add("North",b1);
b5=new Button("non-teaching staff"); this.add("Center",b2);
this.add(b1); this.add("South",b3);
this.add(b2); this.add("East",b4);
this.add(b3); this.add("West",b5);
this.add(b4); }
this.add(b5); }
} class Demo
} {
class Demo public static void main(String[] args)
{ { MyFrame f=new MyFrame();
public static void main(String[] args) }
{ }
MyFrame f=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

3. Grid Layout Fields of BoxLayout class

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.

3. GridLayout(int rows, int columns, int hgap, int


vgap): creates a grid layout with the given rows and
columns alongwith given horizontal and vertical
gaps.

6. CardLayout

It arranges two or more components having the same


size. The components are arranged in a deck, where all
the cards of the same size and the only top card are
4. GridBagLayout visible at any time. The first component added in the
container will be kept at the top of the deck. The default
It is a powerful layout which arranges all the
gap at the left, right, top and bottom edges are zero and
components in a grid of cells and maintains the aspect
the card components are displayed either horizontally
ratio of the object whenever the container is resized. In
or vertically.
this layout, cells may be different in size. It assigns a
consistent horizontal and vertical gap among Constructors of CardLayout class
components. It allows us to specify a default alignment
for components within the columns or rows. CardLayout(): creates a card layout with zero horizontal
and vertical gap.
5. BoxLayout
CardLayout(int hgap, int vgap): creates a card layout
It arranges multiple components in either vertically or with the given horizontal and vertical gap.
horizontally, but not both. The components are
arranged from left to right or top to bottom. If the Commonly used methods of CardLayout class
components are aligned horizontally, the height of all
components will be the same and equal to the largest public void next(Container parent): is used to flip to
sized components. If the components are the next card of the given container.
aligned vertically, the width of all components will be
the same and equal to the largest width components. public void previous(Container parent): is used to flip
to the previous card of the given container.

public void first(Container parent): is used to flip to


the first card of the given container.

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 void last(Container parent): is used to flip to 2. Button


the last card of the given container.
A push button is the frequently found GUI control. A
public void show(Container parent, String name): is push button or a button can be created by using
used to flip to the specified card with the given name the Button class and its constructors which are given
below:

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 getLabel() – To retrieve the text on the button.

Label(String str)

Label(String str, int how) public class MyFrame extends Frame


{
The parameter how specifies the text alignment. Valid Button b1, b2, b3;
values are Label.LEFT, Label.CENTER or Label.RIGHT. MyFrame()
{
Methods available in the Label class are as follows:
setSize(400, 200);
setTitle("My Application");
void setText(String str) – To set or assign text to the
setLayout(new FlowLayout());
label.
setVisible(true);
String getText() – To retrieve the text of a label. b1 = new Button("Red");
b2 = new Button("Green");
void setAlignment(int how) – To set the alignment of text b3 = new Button("Blue");
in a label. add(b1);
add(b2);
int getAlignment() – To get the alignment of text in a add(b3);
label. }
public static void main(String[] args)
{
MyFrame m= new MyFrame();
public class MyFrame extends Frame
}
{
}
Label myLabel;
MyFrame()
{
setSize(400, 200);
setTitle("My Application"); 3. Text Fields
setLayout(new FlowLayout());
setVisible(true); A text field or text box is a single line text entry control
myLabel = new Label("This is a label!"); which allows the user to enter a single line of text. a
add(myLabel); text field can be created using the TextField class along
with its following constructors:
}
public static void main(String[] args) TextField()
{
MyFrame m = new MyFrame(); TextField(int numChars)
}
} TextField(String str)

TextField(String str, int numChars)

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

Following are various methods available in TextField TextArea()


class:
TextArea(int numLines, int numChars)
String getText() – Retrieves the text in the text field.
TextArea(String str)
void setText(String str) – Assigns or sets text in the text
field. TextArea(String str, int numLines, int numChars)

String getSelectedText() – Retrieves the selected text in TextArea(String str, int numLines, int numChars, int
the text field. sBars)

void select(int startindex, int endindex) – To select the


text in text field from startindex to endindex – 1.
In the above constructors, numLines specifies the
boolean isEditable() – To check whether the text field is height of the text area, numChars specifies the width of
editable or not. the text area, str specifies the initial text in the text area
and sBars specifies the scroll bars. Valid values of
void setEditable(boolean canEdit) – To make a text field sBars can be any one of the following:
editable or non-editable.

void setEchoChar(char ch) – To set the echo character of


a text field. This is generally used for password fields. SCROLLBARS_BOTH

boolean echoCharIsSet() – To check whether the echo SCROLLBARS_NONE


character for the text field is set or not.
SCROLLBARS_HORIZONTAL_ONLY
char getEchoChar() – To retrieve the current echo
character. SCROLLBARS_VERTICAL_ONLY

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.

void insert(String str, int index) – To insert the given


string at the specified index.
4. TextArea
void replaceRange(String str, int startIndex, int
A text area is a multi-line text entry control in which endIndex) – To replace the text from startIndex to
user can enter multiple lines of text. A text area can be endIndex – 1 with the given string.
created using the TextArea class along with the
following constructors:

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.

void setLabel(String str) – To set the text of a checkbox. }


public static void main(String[] args)
{
MyFrame m = 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

7. Dropdown Boxes (choice) 8.List Boxes

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

public class MyFrame extends Frame


{
List myList;
MyFrame()
{
setSize(400, 200);
setTitle("My Application");
setLayout(new FlowLayout());
myList = new List();
myList.add("CSE");
myList.add("ECE");
myList.add("EEE");
myList.add("IT");
add(myList);
setVisible(true);
}
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

You might also like