Core Java Some Important Points To Remember
Core Java Some Important Points To Remember
Its just collection of some points but not the entire notes on Core
Java and I am presenting this notes by thinking that you know Core
Java well (at least basics and important concepts)
My sincere thanks to all students and faculty who has typed and
reviewed this material.
Madhav L
(www.geocities.com/megamadhu
http://free.7host06.com/lmadhav)
Contents:
Introduction
Basics
AWT
I-O Streams
Threads
Networking
OVERVIEW OF C++:
C++ was invented by "Bjarne Stroustrup" in 1979, Bell Laboratories, Murray
Hill,New Jersey. Stroustrup initially called the new language C with classes. In 1983,
the name was changed to C++, C++ extends C by adding object-oriented features.
C++ was standardized in November 1997, and an ANSI/ISO standards for C++ is
now available.
NEED OF C++:
The use of structured programming language (like C) enabled the programmers to
write, for the first time, moderately complex programs fairly easily. However, even
with structured programming methods, once a project reaches a certain size, its
complexity exceeds what a programmer can manage. By the early 1980's many
projects were pushing the structured approach past its limits. To solve this problem, a
new way to program was invented, called Object Oriented Programming (OOP).
OOP is a programming methodology that helps organize complex programs through
the use of Inheritance, Encapsulation and Polymorphism.
class Example{
//program begins with a call to main()
public static void main(String args[ ])
{
System.out.println("hello world");
}
}
Note: In Java source file is officially called a 'compilation unit'. This is a text file that
contains one or more class definitions.
In Java all the code must reside in a class. By convention, the name of that class
1
should match with the name of the file that holds the program. Java is case-sensitive.
To run the program: You must use java interpreter, called java. Java byte code is the
intermediate representation of your program that contains the instructions the java
compiler will execute
In java, all program activity occurs within xxxe. This is one reason why all java
programs are (at least a little bit) object oriented. All java applications begin
execution by calling main().
args[]: Receives any command line arguments present when the program is executed.
void: Simply tells the compiler that main() does not return a value.
TCO: Total cost of ownership is also considered, while developing the application.
Delphi developed by Borland is 20% faster than VB. but that is failed because of the
less marketing strategies.
Generally 50% of the features are not useful to the customers, using any software, but
to capture as many no of customers, all the features are introduced by the s/w
developing companies.
2
Building the s/w (compiling + linking = building) in multiple pieces, so that any bugs
in any of the piece, we can modify that particular piece very easily, without damaging
the entire s/w.
Product Product
10MB 10MB
Maintaining the Source in UNIX: Source must be written in n number of files instead
of one single file
Main() Abc()
{ {
xyz(); …..
abc(); ……
cbj(); …. }
}
Object file contains m/c level language instructions and some information.(functions)
Format used in UNIX is COF format (Common Object File Format)
main
abc
xyz
Magic no
Optional Info
Fun1() Rajesh1
Fun2() Rajesh 2
Optional Information: Information depends upon the operating system. Here multiple
3
numbers of sections are available.
Protocol: Set of standards that are used to communicate between two entities.
Processors:
Not all the CPUs are going to support the same instructions. Every CPU has its own
instruction set. Instruction codes for the different CPUs are different, even though
they support all the operations.
You need to create separate exe files for different processors. Using the existing
instructions, simulate the instructions that we need.
Processor + OS
Program written in 'C' language using Intel 386 on windows, should not be executed
on the other o/s. Execution produced by Windows o/s is portable executable (P.E). In
Linux o/s, it is in ELF.
When you have additional s/w at the o/s level and underlying hardware it is possible
to run the windows executable on any other Platforms.
Ex: wine tool using this tool we can run the Windows executable on Linux.
XVM I 386
C Compiler + X-Compiler
Linker Java compiler
4
The purpose of the wine tool is to simulate the windows exe on Linux Platform.
XIS XIS
XVM XVM
Linux Windows
I 386 I 386
Advantage: We can run the final universal format exe File in future platforms without
any Modifications using XVM, which is going to simulate the real o/c
JVM:
Java Virtual Machine is a piece of s/w that runs your class file in which they stores
the o/p. This will convert the byte code into the m/c dependent code. JVM is to
simulate the concept.
Yes. Compiler takes the instructions and generates the output according to the way in
which you want. to generate JCF we can use any language, but general choice is java.
Ex: smalltalk
5
Can I generate the output in portal executable or elf format without using JVM?
Yes, but we can't run this exe on the other platforms.
Customer need not required to install JDK, only JRE is enough to run the Java byte
code.
rt.jar-> Java archive.
Third-party vendors who are developing the JDK ,JVM, and JRE:
Blackdown.org -- ported the JDK to support Linux.
Transvirtual -- Java on Linux m/c's.
Towerj -- Much more efficient than Sun Microsystems JDK and JRE.
JRocket -- Is the best for windows boxes.
Magin no
10110101
optional Inf
main() or start()
6
Winmain() is used in windows o/s instead of main(). Windows can take more
arguments than main() in 'C' Language which can take two arguments.
Class Hello{
Public static void main(String ar[]){
System.out.println("Hello World");
}
}// saved in file Hello.java
Compiler produces class Hello.class. Class name is same for source code, developed
after the compilation.
When we execute java Hello JVM loads the Hello class file and starts executing the
main method, and prints the output.
javap is Java profiler, used in order to check the internals of the java file.
Actually Java is 8 bits (1 Byte) -- Internal virtual m/c's Storage is 32 bits that's why
byte datatype can be stored as integer type.
7
Operand Stack: is the place on stack where the JVM performs the operations.
Method Stack: is an area where JVM stores the local variables.
Java program:
Class Hello{
public static void main(String a[]{
System.out.println();
int i,j,k;
i = 90;
j = 9;
k = i+j;
System.out.println("k");
}
}
ByteCode:
method void main (java.lang.String[])
0 bi push 90 |
2 bi store_1 |---> constant for every int
3 bipush 9 |
5 istore_2 |
6 iload_1
7 iload_2
8 iadd
10 istore_3
11 return
3 99 store-3
Iadd (90+9 = 99)
2 9 store-2
90 9 99 1 90 store-1
int I value
8
i add -> performs the addition operation on operand stack with the loaded values.
store_3 -> stores the result value after the operation on the operand stack, and stores it
on the method stack.
return -> Take the result value from the method stack.
Load & add -> pop two data items from the method stack, add them and store the data
again on the method stack.
Byte code can be created i many ways. There is no specific rule to create a byte code
because it is created according the program which we have written.
k=i+j+k; :-Java compiler automatically creates the temporary variable and stores the
result in it.
1) k=i+j+k; 2)l=i+j+k;
iload_1 iload_1
iload_2 iload_2
iadd iadd l
iload_3 iload_3
iadd 3 k (k result) iadd k
istore_3 2 i istore_4 j
return 1 i return i
3)i=i+j+k; 4) i=(i+j)*k;
istore_3 istore_3
iload_1 iload_1
iload_2 iload_2
imul iadd
iload_3 3 k iload_3 l
iadd 2 j imul k
istore_1 1 i, i(result) istore_4 j
return return i
Can you write a program that run on JVM without using java, c, c++ languages?
Yes, first write the java class file (JCF) in an assembly language, and use the tool to
convert this into java code which can be run on JVM.
Source (addition program) code written and compiled in 'c' language, should it be
100% portable to all the other platforms?
No.
C language is designed to explore the underlying hardware. Some platforms works on
16-bit machines, which can take the int as 2 bytes, and some are 32-bit machines,
which can take int as 4 bytes. In 32-bit machines the range for int value is greater, but
it is out of range to the 16-bit machines.
Portable:- Something it is easy to carry out. But we can write 100% portable to all the
platforms by declaring 'long int' in 16-bit machines and just 'int' in 32-bit machines.
While designing the programs that are 100% portable to all the platforms, the designer
must be careful.Knowledge about the operating system and the underlying hardware.
16-bit m/c's --> The m/c's which performs 16-bit operations.
32-bit m/c's --> The m/c's which performs 32-bit operations.
9
Design concepts of Java:-
Java uses Unicode character set instead of ASCII, which is universally accepted
standard. Here every char requires 16-bits.
In Unicode character set,there are codes for Telugu alphabets also. (Refer
www.unicode.org)
1.Numeric datatype:
Floating point
float (32 bits) double (64 bits)
b) Integer
byte (8 bits) short (16 bits) integer (32 bits) char (16 bits) long (64 bits)
Max range of values stored by byte < short < int < long datatypes.
Char datatype is considered as unsigned Integer, because it takes only +ve values.
10
Min value store = -2^(n-1).
Note:- This is not applicable to the char datatypes.
Int byte are declared at run-time, how many bits of memory taken by each of them?
According to Java Byte should occupy 8 bits, short-16 bit, int-32 bits. But there is no
special instruction to operate datatypes. All these datatypes internally treated as int
datatype.
A virtual m/c implementer may choose to represent a byte available internally using
32-bits.But, the JVM implementer has to choose that a value less than -128 or >127
can never be stored inside a variable that is declare as byte.
But there is a special support for arrays of type byte, char, short and int.
Ex:-
class Hello{
public static void main(String args[ ]){
Byte i,j,k;
i=90;
j=9;
k=i+j;
k=(byte)(i+j);
}
}
Equivalent Byte code:
0 bipush 90
2 bistore_1
3 bipush 9
5 bistore_2
6 biload_1
7 biload_2
8 i2b
9 iadd
10 istore_3
11 return
11
Error will occur, external type casting is required. Because internally i,j treats as an
int ,so byte cannot store int values.
Note: There are no instructions from byte to in, but there are instructions from int to
byte & int to float.
When we convert a big data type to small data type there is a chance that we may
loose some information. So, almost all the languages enforce the developer to use a
'type cast' operator while converting big data type to small data type.
In Java variables cannot be used without initialization.
This is one type of representing an int-literals, and the another type is:
DIL|OIL|HIL
Decimal Int-Literals:
decimal digit
decimal digit decimal digits
(or)
decimal digit(decimal digits)*
--> 0 or more decimal digits.
decimal digit (decimal digits)?
? --> 1 or more decimal digits.
Parsing: Reading the code and printing it in the meaningful units is known as
""parsing .
12
Ex:- int i = 64 ;
1 2 3 4 5 (all these are known as 'tokens").
Hexadecimal Int-Literals:-
OX
(or)
0[x|x](hexadecimal digits)*
0[x|x](hexadecimal digits)?
Character Literals:-
Char ch= 'character';
|-->(A to Z | a to z).
float & double:-The way in which you write the double literals is same as the
floating point literals. Because of this you should use
float f= 22.2f or F to represent the floating point literals.
2) int i= 22.2
s.d.t = l.d.t. --> unsafe.
Any expression that used integer result in the test condition is known as "Integer
Expression". This is for 'C' - language but in Java Boolean expression will be used
inside the if statement.
if(Boolean Expression){
...
...
}
13
if (22) --> not valid in java, but valid in 'C'.
The compiler may rejects: the language conversion cannot be done in this case.
There are two boolean variables b1 and b2. Can I add these two variables (b1+b2 or
b1>b2 or b1<b2)?
We cannot add these two boolean variables. '<' or '>' should not be allowed with
boolean datatypes. There is no such type of conversion.
But b1==b2 is acceptable.
Composition of datatypes:
When language designers design a language they define a set of primitive datatypes,
for every primitive datatype they define composition of datatypes and the operations
that can be operated on a specific datatypes.
If statement:-
s>if(test condition)
statement | block of statements
(no:of statements enclosed within the braces({ })).
{
stmt1;
stmt2;
|
|
|
stmtn;
}
If-else :-
if condition
stmt;
else
statement | block of statements;
Note: There is no 'If-elseif' statement in any language. A language designer need not
define 'if-elseif' statement when a programmer writes 'if-elseif' statements the
compiler actually uses the definitions of if-else and if statements internally.
14
result of the expression is compared with the label. If one of the case Label matches,
the Statements following that case label will be executed till a break is encountered.
If none of the case Label matches, then the statements following the default: will be
executed.
15
...
case 'j':
(is correct)
Ex: final int j;
...
...
case j:
(is wrong)
final --> indicates that the value of a variable cannot be modified after assigning it to
a value.
A 'final' variable can be used as a part of case label, but we have to make sure that
'final' variable is initialized before the case label.
Note: Switch only takes int constants as case labels, it can't take char constants.
Compiler automatically converts char to int, that's why switch is accepting the char
constants as the case labels.
SE: Definition
Assignment
preIncrementExpression
preDecrementExpression
postIncrementExpression
postDecrementExpression
MethodInvocation --> calling method on function class Instance creation Expression.
In for loop you can't write more that one declaration statement in the for initialization.
Ex:
for (int k=0,float f=1.12f;k<5;k++)
in the above float f=1.12f is not valid.
As part of forUpdate any number of for update statement can be written separated by
commas.
As part of statement expression can be allowed in for init and for update.(Method
invocation is also valid in for update).
Ex:- for(i=0,i<5;i++,System.out.println(“two”))
In the case of for init and for update the execution occurs from left most expression to
right most expression.
As part of the for update, we can use any thing that can be treated as statement
expression. According to Java language syntax an "if statement" cannot be considered
as statement expression.
Ex:
for(i=0;i<5;i++,if(i==3) System.out.println(i))
(In the above code if statement is invalid)
16
Comments in coding should be an average of 100% to 150% for every 10 lines of
code. Try to write the comments before you start writing the function i.e. outside the
function.
i=0;
j=i+k; these are known as self documented code.
We can also design the language without using 'for' and 'while' loops (using 'goto'
label)
loopout:
'goto is used here to come out of both the loops(outer loop).If break; is used it comes
out of the current loop. But the outer loop will get executed.
Example:-
for(i=1;i<5;i++)
{
System.out.println(i);
if(i==3)
break; continue;
System.out.println("raj");
}
17
for(i=1;i<5;i++){
System.out.println(i);
if(i!=3)
System.out.println("raj"); }
When a break; statement is used in a for loop, the execution of the loop is stopped
when the break is executed.
When a continue statement is used inside a loop the statements following the continue
will be skipped for that iterations.
When a break; statement is used without a label the loop i.e. initialized by the label
will be broken.
Ex:-
xyz: for(i=0;i<5;i++)
{
System.out.println(i);
for(j=0;j<5;j++)
{
System.out.println(j);
break xyz;
System.out.println("xyz");
}
System.out.println("ABC");
}
Note: break; should be used inside the loop, otherwise it will gives an error at
runtime.
When a break is used with a label the compiler searches for the label in the same loop
or in the outer loops.
Check whether java language allows using multiple labels for the single statement.
Try with this Ex: ABC:xyz:System.out.println("raj");
If there is no error, then java language allows
Ex:
xyz: for(i=1;i<5;i++){
System.out.println("one");
for(j=0;j<5;j++){
System.out.println("two");
if(j==2)
continue xyz;
System.out.println("three");
}
System.out.println("four");
}
Compile the above program with the condition j==2 and check the result. Also check
the program with the condition (j==2)&&(i==2)
WHILE LOOP: We can write a program without using a for loop,i.e all our for...
loop programs can be converted to while... loop.
18
Ex:- (Note: In A and B below the outputs will be same)
For(i=0;i<5;i++)
{
System.out.println(i);
}
int i;
i=0;
while(i<5)
{
System.out.println(i);
i=i+1;
}
Do...loop:
i=0;
while(i<5)
{
System.out.println(i);
i++;
}
i=0;
do
{
System.out.println(i);
i++;
while(i<5);
}
do
{
read int();
read int();
char c=getchar();
}while((c='y')||(c='y'));
while(true)
{
read int();
read int();
if(c!='y')
break;
}
Come out with the designs such that a developer can easily identify the bugs which
will reduce the total time taken to identify the bugs.
19
MODULAR DESIGN: Instead of designing the project or s/w as a single piece,
design a product in n number of pieces. If any bugs occurred then that particular
bugged piece can be modified and replaced. To do this it takes very less time when
compared to the product as a single piece. Because of this total maintenance cost will
be reduced.
P P P
P
P P P
P
Developer2: Saw the design and find out that p2 and p4 depends on p1.So if any
modification is done to the p1 should affect to both p2 and p14.In this case p1,p2 and
p4 are treated as one part, and p3 treated as another part.
There should not be an interdependency in the parts designed because finding out the
inter dependency in a software product is difficult.
Change of the code in one part or any part of the product requires the change of the
code in another part is known as "Monolithic Design".
Write the code to improve the performance of the module in the module itself, instead
of writing the ones developers) own functions.
DB Scanner Network
Server
If the product is developed with 3 modules, any interaction to that particular module
should be done by writing the code in that particular module. In such a case any bugs
that are occurred can be easily identified and that particular module can be tested and
modified. Because of this time is reduced to identify the bugs.
Instead of writing like this, if a developer writes the separate function to interact with
20
the database, and the product is released to the client. After some time, client reports
that he was getting an error while interacting with the database, and if one who
developed that database module is not available. Then it is very difficult to the other
person or a developer to identify that bug because he will never concentrate on the
separate functions developed by the first developer.
Try to write the code to improve the performance according to the standard design
given by the project manager, instead of writing your own functions.
Reasons why 'C' projects fails:(and why new languages are developed ?)
Most of the c projects fail because of the developers fault but not because of the
language.
1) Struct abc{
int a;
int b;
int c;
};
Composition: Set of variables declared in a structure. (what can be stored in the
datatype)
2) Struct Emp{
int sno;
int basicsal;
int hra;
int da;
};
In C language we can define our own datatypes by using structures, when a structure
is defined. 'C' language developer can define the composition of the datatypes but not
the operations that can be performed on that datatype.
For example an Emp datatype can be define by the developers, where the developer
can decide how to store the information about an Emp in a program. But the
programmer has no way of directly representing a set of operations that can be
performed on Emp.
Developer2: Develops the hikesal() function. It is working well. But if there are
10,000 records then this function is very slow. Then he use his own way to improve
21
the performance of the function hikesal(). He writes another function to improve the
performance, or uses another datatype.
Developer2 has done this without consulting developer1 or Project Manager. If there
are 10,000 functions it is very difficult to identify the bugs.
He performed the operations that are illegal, i.e. not according to the design
document.
If the compiler restricts the user not to perform the user operations, then this type of
mistakes should not be occurred.
When we are developing a project in 'C' language, we must design a project such that
the document should be clear and indicating the composition of the datatypes and the
operations that can be performed on that datatypes. For Ex. in a project the designer
can clearly mention that hikesal(), calculatesal(), and changedept() should be called
whenever an operation has to be performed on Emp datatype. if all the developers in a
project follows the same rules, if at all a bug is reported related to Emp datatype, we
can rectify the bug very easily. Since the operations an Emp performed only using the
set of functions identified during the design.
Since 'C' language compiler doesn't restrict the developer to add his own code to
perform some operations directly on a structure. Most of the developers using 'C'
kind of language tend to make mistakes writing the code which directly access
structures in their own way.
C++: Let us assume that there exists a new Language called 'NewC' language, which
allows the developer to create his own datatype by defining composition and the
operations that can be used on that datatype.
Struct Emp{
int eno;
int basicsal;
int hra; //this defines the composition.
int da;
hikesal(){...} //defines the operations.
calcsal();
};
In the above example the compiler knows that the legal operations that can be
performed on Emp datatype.
e.hikesal() --> To call the operations.
With this setup developer2 cannot write his own code which operates directly on Emp
datatype. If he finds that the hikesal() function running very slow, instead of writing
his own code to increase the salary. He will suggest to do the modifications to
hikesal() developed by developer1.
Note: Even by using C kind of language we can develop the applications properly, but
there are very few restrictions. When a normal developer develops a project in C
language instead of carefully using these restrictions they are misusing, ultimately
resulting in so many bugs in the project.
22
Abstraction:
Ex: In Telephone Dialing a number is known as Interface and Complex circuit which
takes the keystrokes of a user and perform the operation, is known as Implementation.
Any complex device can be operated by knowing the Interface, even if you don't
know the Implementation.
In C language the prototype or definition (or the parameters or arguments that can be
passed) of that particular function is known as "Interface".
The code written by the developer, what should be done when that function is called
by the user is known as "Implementation".
Abstracting: Giving the details which are required to the user and hiding the complex
details which are not required to the user. This is also allowed in Assembly Language.
In a 'NewC' language ADT(Abstract Data Type) is used to define user datatypes like
structure in "c".
ADT DATE {
int year;
int month;
int day;
sub_Date(){--}
sub_Days(){--}
add_Days(){--}
};
10 10
objects objects
Total there are 40 items or objects. But all these objects are classified into 4(types)
23
different classes.
When designing a mechanical instrument, we need to come out with the blue-print for
the creation of different objects. When we apply the similar kind of design for
software development we can express these blue-prints programmatically by using the
abstract datatypes (ADT).
2) ADT Connectingrod{
float length;
float diameter;
float realradius;
rotate(){--}
}
24