Core Java - Part1
Core Java - Part1
Core Java - Part1
com
Core JAVA
1
aravindonlineclasses.com
INTRODUCTION
Introduction
Java Buzzwords
Installing JDK Sofware
class & object
keywords
Identifiers
Datatypes
Arrays
main method
command line arguments
Introduction
The early 1950 languages such as Fortran and Cobol are Specific purpose languages. The main drawback
with specific purpose languages is they are specific to a particular purpose. For example, Fortran is
meant for developing only scientific applications, and Cobol is meant for developing only business
oriented applications.
In early 1960s, the BCPL (Basic Combined Programming Language) language was developed for
developing all types of applications i.e., BCPL is a general purpose language. The drawbacks in BCPL are
solved with a new language called ‘B’. Even though ‘B’ is a general purpose language, it has its own
drawbacks. To solve these problems, a powerful, efficient, reliable language “C” was developed by
Dennis Ritche in 1972.
The ‘C’ language follows Structured Programming approach.
The main drawback with Structured Programming languages such as ‘C’ is its complexity increases once
the project size reaches a certain size.
To solve this problem, a new way to program was invented called Object Oriented Programming (OOP).
OOP programming methods helps us to organize (simplify) complex programs through Encapsulation,
Inheritance, and Polymorphism.
C++ was developed by Stroustrup in 1979.
Two main drawbacks with C++ language are : Platform dependent and won’t support Internet and
WWW.
To solve these problems, the James Gosling developed a new language called JAVA at sun Microsystems
in 1991, which is platform independent and supports WWW & Internet.
Java was initially called as “OAK” after he saw oak tree outside of his window at sun. Later he came to
know that the Language “OAK” already existed in the market. When a group of sun people visited a local
coffee shop, the name “JAVA” was suggested. Java is a slag term for coffee.
Java Buzzwords
The following are Java buzzwords:
1. Simple
2. Object Oriented
2
aravindonlineclasses.com
3. Robust
4. Platform Independent
5. Portable
6. Multithreaded (Or Parallel Execution)
7. Distributed (Or Networking)
8. Secure
9. Dynamic
I. Simple
Java is a simple language because of the following reasons:
C++ is evolved from C).
Java is syntactically related to C++ which is a direct decedent from C (i.e.,
Most of the syntax and characters are inherited from these two languages.
Some of the most confusing concepts in C/C++ are either left out of java or implemented in a
cleaner way.
For example: Pointers are completely eliminated from java. The disadvantage with pointers are
overriding memory and corrupting data. In java, the memory management is implemented in a
cleaner way using Garbage Collector (GC)
V. Portable
The size of the primitive data types are fixed on all platforms.
Also, binary data is stored in a fixed format, eliminating the “big endian | Little Endian” confusion.
VIII. Secure
Java provides several layers of protection from dangerous code, virus, Trojan horses. Java security
is provided from the Java Architecture itself. Also, Java security can be provided using security API.
IX. Dynamic
It was designed to adapt to an evolving environment.
4
aravindonlineclasses.com
The UML (Unified Modeling Language) notation for the class is:
<class name>
<fields>
<Methods>
Example:
class Box{ Box
//Field declaration int Width;
int width; int height;
int height;
int depth;
int depth;
//Constructor
Box(int, int, int)
Box(int w, int h, int d){
in volume()
width = w;
height = h;
depth=d;
}
//Method declaration
int volume(){
return width*height*depth;
}
}
object
Instance of a class is called as an object. In java, object is created using ‘new’ keyword.
The object creation process involves following three steps:
Declaring reference variable
Construction an object using ‘new’ keyword.
Assigning Reference value (address) to reference variable.
Example:
Box b = new Box(1,2,3);
The fields of a class is also called as attribute, properties, instance variable, or data member.
The methods of a class is also called as behavior, operation, instance method, or method member.
The data member and method member of a class is called as member of a class.
The new keyword creates an object and returns the reference value to the reference variable.
Keywords
The keyword has a predefined meaning in the programming language.
aravindonlineclasses.com
Identifiers
The name in a program is called an Identifier. Identifier is a sequence of characters. Identifiers are the names
of the variables, methods, classes, packages, interfaces, arrays, enumerations, labeled names, etc.
Example:
class Welcome{
public static void main(String[]
args){ int age = 10;
System.out.println(“Welcome program”);
}
}
Datatypes
In java, the data types are grouped into two categories:
Primitive types
Reference types classes, interfaces, exceptions, errors, enums, annotations, and arrays
Primitive types
There are 9 primitive types in java.
Below table summarizes the categories of the primitive types:
Category Primitive types
integers byte, short, int, long
floating point numbers float, double
Characters char
Booleans boolean
empty set data type void
Below table summarizes the corresponding wrapper classes, size, range, and default values:
6
aravindonlineclasses.com
Primitive type Wrapper type Size (in bytes) Range Default values
byte java.lang.Byte 1 -128 to +127 0
short java.lang.Short 2 -32,768 to + 32,767 0
31 31
Int java.lang.Integer 4 -2 to +2 – 1 0
63 63
long java.lang.Long 8 -2 to +2 – 1 0
float java.lang.Float 4 -3.4e38 to 3.4e38 0.0F
double java.lang.Double 8 -1.7e308 to 1.7e308 0.0
Char java.lang.Character 2 0 to 65,535 Blank Space( ‘ ‘)
boolean java.lang.Boolean N/A N/A false
void java.lang.Void N/A N/A N/A
Note:
1. By default, all integers are initialized with 0.
2. By default, all floating point numbers are initialized with 0.0
3. By default, all characters are initialized with blank space.
4. By default, all booleans are initialized with false.
5. By default, all reference types are initialized with null.
6. The size of the primitive data types are fixed across all operating systems.
7. The java supports only signed integers but unsigned characters.
Arrays
Introduction
Array Declaration
Array Construction
Array Initialization
Annonymous arrays
length vs length()
Disadvantages with arrays
Introduction
An array is a group of homogeneous elements i.e., all elements in an array have same data type.
The array is an index based collection whose index starts at 0 and ends with index (n-1), where ‘n’ is the
number of elements in an array.
The size of an array is fixed and cannot be changed.
In java, arrays are created dynamically at runtime using ‘new’ keyword, hence, arrays are objects.
The element types in an array are either Primitive or Object (reference) type.
Array Declaration
Single dimensional arrays are declared in following ways:
<array type> <array name>[];
(or)
<array type>[] <array name>;
(or)
<array type> []<array name>;
Example:
int arr1[], arr2[]; //Both arr1 and arr2 are arrays.
7
aravindonlineclasses.com
Array Construction
In java, arrays are dynamically created at runtime using ‘new’ keyword, hence, arrays are objects.
Syntax:
<array type>[] <array-name> = new <array type>[<array-size>];
Example
int[] arr = new int[10];
8
aravindonlineclasses.com
Main method
public static void main(String[] args){}
args[0] args[1]
Example:
//Addition.java
class Addition{
public static void main(String[] args){
int a = Integer.parseInt(args[0]); //”10” 10 int
b = Integer.parseInt(args[1]); //”20” 20 int sum
= a + b; System.out.println("Total="+sum);
}
}
Java Addition 10 20
O/P:
Total=30
9
aravindonlineclasses.com
Arithmetic Operators
The arithmetic operators are +, -, *, /, % (Remainder).
In arithmetic expression, if the operand type is byte, short, or char, then they are automatically promoted
to int.
Pre increment
++i adds 1 to the value in ‘i’, and stores the new values in i. It returns the new value of the expression. It is
equivalent to the following statement.
i=i+1
int result = i;
return result;
Post incremet
j++ adds 1 to the value in j, and stores the new values in j. It returns the old value of the expression. It is
equivalent to the following statement.
result=j;
j=j+1
aravindonlineclasses.com
return result;
Pre decrement
--i subtracts 1 to the value in i, and stores the new values in i. It returns the new value of the expression. It
is equivalent to the following statement.
i=i-1; result =
i; return
result;
Post decrement
j-- subtracts 1 to the value in j, and stores the new values in j. It returns the old value of the expression. It is
equivalent to the following statement.
result=j;
j=j-1
return result;
Relational operators
The relational operators are <, <=, >, >=. All relational operators are binary operators. The evaluation results
in a boolean value.
Example:
System.out.println(1< 2); //true
! Logical Complement
Truth table for boolean logical operators
X Y !X X&Y X|Y X^Y
True True False True True False
True False False False True True
False True True False True True
False False True False False False
For boolean logical AND, OR, and XOR operators, both operands are always executed.
Example:
Int i = Integer.parseInt(args[0]);//”10” 10
if( i > 10 & i++ < 20){} // ’i’ is incremented irrespective of first condition.
Example:
Int a = Integer.parseInt(args[0]);
Int b = Integer.parseInt(args[1]);
if((b!=0) && (a%b==0)){ //Never throws ArithmeticException
System.out.println(“No exception”);
}
12
aravindonlineclasses.com
Assignment Operators
There are three types of assignment operators:
Simple assignment operator
Exmaple:
int a = 10;
Chained assignment operator
Example:
int a, b,c;
a = b = c =10;
Compound assignment operator
The following are the possible compound assignment operators: +=,-=,*=,/=,%=,&=,|=,^=
Example:
sum += x; //which is equivalent to sum = sum + x;
Type casting
Primitive or Reference type widening does not require explicit cast.
But, either Primitive or Reference type narrowing requires explicit cast.
Example:
float f = 10.10F;
//int i = f; //Compilation Error saying “Incompatible types”
Int i = (int)f; // To avoid compilation error, use type casting
CONTROL FLOW
Control flow statements govern the flow (order) of control (execution) in a program during execution.
There are three main categories of control flow statements:
Selection statements:
if
if-else
else if ladder
switch
Iteration statements:
while loop
do-while loop
Basic for loop
Enhanced for loops (JDK1.5)
Transfer statements:
break
continue
return
try-catch-finally
throw
assert
Selection statements
The selective statements are used to execute group of statements (block of statements) at most once
i.e., zero or once.
I. if() statement
aravindonlineclasses.com
It is used to decide whether block of statements are executed or not based on the <condition>.
Syntax:
if(<condition>){
<statement(s)>
}
The <condition> must be boolean value but not numeric number. The if block will be executed
only if the <condition > is true.
Example:
Int age = Integer.parseInt(args[0]);
If(age < 18){
System.out.println(“Your age does not permit to login to our website.”);
}
II. if-else
The if-else statement is used to decide between two actions.
Syntax:
If(<condition>){
<statement(s)>
}else{
<statement(s)>
}
If the <condition > is evaluated to true then if block is executed, otherwise else block is executed.
Example:
int age = Integer.parseInt(args[0]);
If(age < 18){
14
System.out.println(“Your age does not permit to login to our website.”);
}else{
SOP(“Logged into Inbox”);
}
if(false){ }else
if(false){
}else{ //Else block is executed since all above if() blocks are evaluated to false.
aravindonlineclasses.com
IV. switch
Switch statement is used to choose one among many alternative actions.
Syntax:
switch(<switch expression>){
case label1: <statement(s)>
case label2: <statement(s)>
…
case labeln: <statement(s)>
default: <statement(s)>
}
The valid <switch expression> types are:
byte, short, int, char, but not long
Byte, Short, Integer, Character, but not Long
Iteration Statements
The iterate statements are used to execute block of statements repeatedly until the boolean
<condition> becomes false.
I. While loop
In case of while loop, the <condition> will be evaluated before executing body.
Syntax:
while (<condition>){ <
body>
}
The <condition> is always boolean value.
Program: Write a program to print numbers from 1 to 10.
aravindonlineclasses.com
Int I =1;
While(I <=
10){
System.out.print(I+”\t”
); I++;
}
Note:
1. Enhanced for loop is used only with arrays and collections but not for general purpose.
2. Enhanced for loop cannot be used to retrieve elements in reverse order.
Transfer Statements
I. break
The ‘break’ is used to come out of the loops.
We can use break statement in one of the following cases:
Inside loops
Inside switch
Example:
For(int I=0 ; I<10; i++){ For(int
j=0; j<10; j++){
If(i==j) break; //the nearest for loop will be terminated.
}
}
II. Continue
The continue statement is used to transfer the execution back to the start of the loop i.e., the
remaining statements after continue will be skipped.
Program: Write a program to add even numbers but print odd numbers.
Int sum = 0;
for(int i = 0; i<=10; i++ ){
if(i%2 == 0){ //even number
sum+= I; //Adding even numbers
continue;
}
System.out.print (i+”\t”); //Printing odd numbers
}
Sop(“The sum of even numbers is:”+sum);
III. return
The return statement is always used from method block. The return statement is used to stop
execution of a method and transfer control back to the method calling.
There are two forms of the return statement:
return; //Optionally used with methods whose return type is void or from
constructor.
aravindonlineclasses.com
return <expression>; //Must be used with methods whose return type is other than void.
A void method need not have a return statement – in which case the control normally returns to the
caller after the last statement in the method’s body has been executed. However, a void method can
optionally specify the first form of the return statement – in which case the control immediately
transferred to the method caller.
Packages
In java, package is a directory structure which contains group of related classes, interfaces, enums,
exceptions, errors, annotations, or subpackages.
Example:
Package Directory Types
java.lang java\lang String, System, Object, Integer, etc
java.io java\io InputStream, OutputStream, Reader, Writer, etc
java.util Java\util List, Set, Map, Vector, Hashtable, etc
At most one package declaration can appear in a source file, and it must be the first statement in the
source file.
Example:
package online;
//Correct
import java.lang.String;
Use ‘–d’ option to compile classes with package declaration.
aravindonlineclasses.com
Syntax:
Javac -d <directory> <java source file>
Example:
Javac –d . *.java
where ‘.’ Specifies current directory, where the generated class files will be placed.
Example:
package
online; class
Test{
public static void main(String[] args){
System.out.println("Package concepts");
}
}
Compilation:
Javac -d . Test.java
Also, the fully qualified type name must be specified in the java command.
Example:
Java online.Test
To access package types from other packages, use either fully qualified type (<package_name>.<type>) or
import types using ‘import’ keyword.
Modifiers in java
There are 13 modifiers in java:
Private
default
Protected
Public
Final
Static
Abstract
Interface
Synchronized
Transient
Native
Strictfp
volatile
Accessibility Modifiers
In java, there are 4 accessibility modifiers: private, no (or default or package) modifier, protected, and
public.
The below table summarizes the scope of accessibility modifiers:
Scenario Private default Protected Public
Within the same class Yes Yes Yes Yes
Subclass of the same package No Yes Yes Yes
Non subclass of the same package No Yes Yes Yes
Subclass from different package No No Yes Yes
aravindonlineclasses.com
Imports
The given class can be accessible from outside the package using fully qualified type name, however, writing
long names can become tedious.
Example:
edu.online.One obj = new edu.online.One();
The import facility in java makes it easier to access classes from different packages, which will be declared
once using import statement and used it for any number of times just with simple type name.
Example:
import edu.online.One;
One obj = new One();
[Package Declaration]
[Import Statement(s)]
Comments
Java supports 3 types of comments:
1) Multline comments (From C
language) syntax:
/*
….
….
*/
2) Single Line comment (From C++ lanaguage)
Example:
//Tomorrow is a holiday
3) Java doc comments
aravindonlineclasses.com
This is newly added in JAVA. These comments are used to add description about class as well
as methods.
Syntax:
/**
*
*/
21