Javasecondnb
Javasecondnb
History of Java:
Java is a general purpose and object oriented programming language developed by “SUN Micro
Systems” of USA in 1991.
Originally it is called as “Oak” by James Gosling, one of the inventors of the language.
This language ‘oak’ is renamed as java in the year 1995.
Initially java was designed for the development of software for consumer electronics devices like TV’s,
VCR’s, toasters and such other electronic devices.
The main feature of java language is that it is a plat form – independent language.
Java is the first programming language that is not tied to any particular hardware or an operating system.
Programs developed in java can be executed anywhere on any system.
Java language is simple, portable, highly reliable and powerful language.
Features of Java :
1. Complied and Interpreted : Usually a computer language is either complied or interpreted. Java combines
both these approaches thus making java a two stage system. First java complier translates source code into what
is known as byte code instructions. Byte codes are not machine instructions and in second stage, java interpreter
generates machine code that can be directly executed by machine.
2. Platform-Independent and portable: The most significant contribution of java over other languages is its
portability. Java programs can be easily moved from one computer system to another, anywhere and anytime.
Changes and upgrades in operating system, system resources will not force any changes in java program.
Java ensures portability in two ways. First, Java complier generates byte code instructions that can be
implemented on any machine. Secondly, Size of data types are machine independent.
3. Object-Oriented : Java is a true object-oriented language. Almost everything in java is an object. All
program code and data reside within an objects and classes. Java comes with extensive set of classes, arranged
in packages.
4. Robust and Secure :
Java is a robust language. It provides many safeguards to ensure reliable code (correctness).
It has strict compile time and runtime checking for data types.
It is a garbage-collected language.
Java has concept of exception handling which captures serious errors and eliminates any risks of crushing
system.
5. Security: Become an important issue for a language that is used for programming on internet. Threat of
viruses and abuse of resources are everywhere. Java systems not only verify all memory access but also ensure
that no viruses are communicated with an Applet. The absence of pointers in java ensures that programs cannot
gain access to memory locations without proper authorization.
6. Distributed: Java is designed as a distributed language for creating applications on networks. It has the
ability to share both programs and data. Java applications can open and access remote object as easily as they
can do in a local system. This enables multiple programmers at multiple remote locations to work on a single
project.
7. Simple, Small and Familiar: Java is a small and simple language. Many features of c and c++ are not part
of java. Eg: Java does not use pointer, preprocessor’s header file, go to statements multiple inheritance.
Familiarity is another feature of java, because it is modeled a C and C++ languages. Java is simplified version
of C++ language.
8. Multithreaded and interactive: Multithreaded means handling multiple tasks simultaneously. Java supports
multithreaded programs. This means that we need not wait for the application to finish one task before
beginning another. Eg: listen to audio clip while scrolling a page.
9. High Performance: Java performance is impressive for an interpreted language, mainly due to use of
intermediate byte code. Java architecture is designed to reduce over heads during runtime. Multithreading
enhance the overall execution speed of java program.
10. Dynamic and Extensible: Java is a dynamic language. Java is capable of dynamically linking new class
libraries, methods and objects. Java programs support functions written in other languages such as C and C++.
These functions are “native methods”. These are linked at runtime.
2.2 Define an Applet and application in java
Applet:
An application is a program that runs on your computer under the operating system of that computer .
Applications Applets
1)It has only main() function 1)It does not have any main() function
3)It executes the program in the normal platform 3)It executes in web browser (or) applet viewer
4)While we are using we can’t use html tags 4)Here we have to use html tags
5)It does not require internet browser 5)It may be requires internet browser
2.3 Understand Byte codes of Java, JVM
1. All language compilers translate source code into machine code for a specific computer. Java compiler also
does the same thing. But the platform independent nature can be achieved by the following process.
2. Java Compiler produces an intermediate code known as byte code. For a machine that doesn’t exist. This
machine is called ‘java virtual machine’ [JVM] and it exists only inside the computer memory.
3. The following figure shows compiling a java program into byte code.
4. The byte code is not machine specific. The machine code is generated by the java interpreter by acting an
intermediary between virtual machine and the real machine.
Java virtual machine is the heart of entire java program execution process . It is responsible for taking
the .class file and converting each byte code instruction into the machine language .
First of all the .java program is converted into a .class file consisting of byte code instructions by the java
compiler . Now this .class file is given to the JVM
Method area: Method area is the memory block which stores the class code(variables and methods).
Java stacks: Method code is stores on method area . but while running a method it needs some more memory
to store data results .This memory is allotted on java stacks .
Pc(program counter): these are the registers which contain memory address of the instructions of the
methods .
Native method stacks : Java methods are executed on java stacks. Native methods are executed on Native
method stacks .To execute native methods , native method libraries are required . These header files are
located and connected to JVM by a program called native method interface .
Execution engine: This contains interpreter and JIT compiler , which is responsible for converting byte code
instructions to machine code instructions .
We can create a program using any text editor. Assume we have enter the following program
class Simple
We must save this program in file called Sample.java. Filename is same as the class name. This file is called
source file.
Compiling the program: To compile the program in Java language we must run the compiler ‘javac’, with
name of source file on the command line at shown below.
javac Sample.java
If everything is ok, the javac compiler creates a file called ‘Sample.class’ contains bytecode of the program.
Executing the program: In order to execute a java program we use java interpreter to run the standalone
program at the command prompt type ‘java Sample’
Now the interpreter looks for the main method in the program and begins executions from there. When
executed our programs [above program] displays the following output
COMMENTS: Comments are statements in a java program are not read or interpreted by the java compiler.
They are used to add more meaning to the code and to provide understanding to the developers.
1. Single line comment: Single line comments starts with double slash (\\) and ends at the end of line.
2. Multiple line comments: For longer comments we can write in multiple lines by starting with a /* and
ending with */.
3. Documentation comments: Documentation comments are used to produce an html file that documents
over program. The documentation comments starts with /** and ends with */.
Keywords: Key word is one which have a predefine meaning in the language. Java has 50 reserved key words.
These key words combined with operators and separators according to syntax. Key words have specific
meaning in java, we cannot use them as variable names, class name and method names.
Java keywords:
Unicode System:
Unicode is a universal international standard character encoding that is capable of representing most of the
world's written languages.
Before Unicode, there were many language standards:
o ASCII (American Standard Code for Information Interchange) for the United States.
o ISO 8859-1 for Western European Language.
o KOI-8 for Russian.
o GB18030 and BIG-5 for chinese, and so on.
JavaSoft people wanted to provide a facility to include characters not only from English but also from
all other human languages to be used in java programs.This will enable the programmers to write and
execute a java program in any language ,which becomes an advantage on internet . this system also
called Unicode system. Unicode uses a 2 bytes so that any character fro any language can be encoded
successfully.
Naming system in java: Naming conventions specify the rules to be followed by a java programmer while
writing the names of packages , classes ,methods, etc .
A package contains classes and interfaces . Names of packages in java are written in small letters
Ex :- java.awt , java.io,java.applet,java.swing
A class is a model for creating objects. An interface is also similar to a class . Each word of class names
and interface names start with capital letter .
Ex: String , BufferedReader, DataInputStream, ActionListener , RandomAcess .
A class contains variables and methods . the first word of a method name is in small letters . then second
word onwards , each new word starts with a capital letter
The naming convention for variables names is same as that for methods
Ex: age , empName
Constants represent fixed values that cannot be altered . constants should be written in capital letters .
Ex: PI, MAX _VAL
Integer types
Integer types can hold whole numbers.
The size of the values that can be stored depends on the integer data type we choose.
Java supports four types of integers as shown in fig. they are byte, short, int, and long.
Java does not support the concept of unsigned types and therefore all java values are signed meaning
they can be positive or negative.
Table shows the memory size and range(-2n-1 to 2n-1-1) of all the four integer data types.
Integer
Floating point
float double
Character type
In order to store character in memory, java provides a character data type called char.
Java uses Unicode to represent characters.
The chara type assumes a size of 2 bytes but, basically, it can hold only a single character.
Unicode defines a fully international character set that can represent all of the characters found in
human languages.
Boolean type
Boolean type is used when we want to test a particular condition during the execution of the program.
There are only two values that a boolean type can take: true or false.
Boolean type is denoted by the keyword boolean and uses only one bit of storage.
All comparision operators return boolean values.
Example program
import java.io.*;
class datatypes
{
public static void main(String args[])
{
boolean t=true;
byte a=10;
short s=5;
int p=15;
long L=1550L;
float f=10.5f;
double d=10.555;
char ch='x';
String str="java";
System.out.println(t);
System.out.println(a);
System.out.println(s);
System.out.println(p);
System.out.println(L);
System.out.println(f);
System.out.println(d);
System.out.println(ch);
System.out.println(str);
}
}
Variables are separated by commas (,) and the declaration statement ends with semicolon (;)
Ex: int a, b;
Float t;
Byte b;
Boolean z;
Example Program:
import java.io.*;;
class Addition
{
public static void main(String args[])throws IOException
{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in))
System.out.println("enter a ,b values");
int a=Integer.parseInt(in.readLine());
int b=Integer.parseInt(in.readLine());
int c=a+b;
System.out.println("addition of two numbers="+c);
}
}
Narrowing: - converting a higher data into a lower data type is called ‘narrowing’.
Ex: int n=66;
char ch=(char)n; //ch contains ‘B’.
Features of Narrowing:-
Here we will loss some data so narrowing is not safe.
eg:- double d= 12.6789;
int n=(int)d; //n stores only 12.
The programmer should use cast operator when going for narrowing. So narrowing is also called as
demotion of data.
Narrowing the data type is also called as Explicit casting.
Example for type conversion :
class AutomaticConversion
{
int a=’x’;
double d=10;
System.out.println(the value of a=+a);
System.out.println(the value of d=+d);
2. Creation of arrays: After declaring an array we need to create it in the memory. Java allows us to create
arrays using new operator as shown below.
It is also possible to combine the two steps declaration & creation into one as shown below.
Ex: int number[ ]=new int[5];
3.Intialization of arrays: The final step is to put values into the array created. This process is known as
initialization. This is done using the array subscripts as shown below.
Array length: Arrays store the allocated size in a variable name “length”. We can obtain the length of the
array ‘a ‘using a. length. Ex: int len=a. length;
write a java program for declaration and initialization of one dimensional array at compile time
class Testarray1{
public static void main(String args[])
{
int a[]={1,2,3,4,5};//declaration, instantiation and initialization
//printing array
for(int i=0;i<5;i++)
System.out.println(a[i]);
}
}
write a java program for declaration and initialization of one dimensional array at runtime
import java.io.*;
import java.util.Scanner;
class Testarray2{
public static void main(String args[])throws IOException
{
Scanner sc =new Scanner(System.in);
System.out.println("enter array length");
int n= sc.nextInt();
int a[]= new int[n];
System.out.println("enter array elements");
for(int i=0;i<n;i++)
a[i]=sc.nextInt();
System.out.println("the elements are");
for(int i=0;i<n;i++)
System.out.println(a[i]);
}
}
Two-dimensional arrays: Two dimensional array are the arrays with 2-indexes (or) subscripts called row &
columns.(or) A two dimensional array represents several rows & columns of data.
Creating two-dimensional array: Creation of array involves three steps.
1. Declare the array
2. Creating memory locations
3. Putting values into the memory location
1. Declaration of arrays: Array in java can be declared in two methods.
Method1-------------------------- type arrayname[ ][ ];
Method2-------------------------- type[ ][ ] arrayname;
Form1 Example: Form2 Example:
int marks[ ][ ]; int[ ][ ] marks;
float avg[ ][ ]; float[ ][ ] avg;
In declaration should not enter the size of an array.
2. Creation of arrays (allocating memory): Java allows to create arrays using “new” operator
Syntax: array name=new type[ ][ ];
Example: write a java program for declaration and initialization of one dimensional array at compile
time
class Testarray3
{
public static void main(String args[])
{
int arr[][]={{1,2,3},{2,4,5},{4,4,5}};
for(int i=0;i<3;i++)
for(int j=0;j<3;j++)
System.out.print(arr[i][j]+"\t ");
}
}
write a java program for declaration and initialization of one dimensional array at runtime
import java.util.Scanner;
class JavaProgram
{
public static void main(String args[])
{
int m, n, i, j;
int arr[][] = new int[10][10];
Scanner scan = new Scanner(System.in);
1. The Arithmetic Operators: These operators are used to perform fundamental arithmetic operations like
addition, subtraction,... There are 5-arithmetic operators in java.
Operato
Description Example
r
+ Addition A+B
- Subtraction A-B
* Multiplication A*B
/ Division B/A
% Modulus B%A
2. The Relational Operators: They are used for the purpose of comparing two operands. They are of 6-types
1) > greater than operator
2) > = greater than(or) equal to operator
3) < lessthan operator
4) <= lessthan (or) equal to operator
5) = = equal to
6) != Not equal to
3. TheLogical operator: These operators used to construct compound conditions by combining 2 or more
relations. Logical operator one of 3-types
--> && logical and operator
--> || logical or operator
--> ! logical not operator
eg:- if (a=1||b==1||c==1) System .out.println ("yes");
4. The Assignment Operators: This operator is to store some value into a variable. It is used in 3-ways.
a) To store a value into a variable eg :- int x=5;
b) To store a value of one variable into another eg:-int x=y;
c) To store a value of expression to a variable, eg - int x=y+z-4;
Note -1) we can't use more than one variable at left hand side of.
eg:- x+y=10; //invalid.
2) We can’t use a literal (or) constant at left head side of eg:- 15=x;//invaded.
Shorthand Notation:-
Syntax: v op=exp;
x=x+10; ==> x+=10;
p=p/100;==>p/=100;
There are following assignment operators supported by Java language:
Operato
Example
r
= C = A + B will assign value of A + B into C
+= C += A is equivalent to C = C + A
-= C -= A is equivalent to C = C — A
*= C *= A is equivalent to C = C * A
/= C /= A is equivalent to C = C / A
%= C %= A is equivalent to C = C % A
5.Increment & decrement Operators: These are used to perform addition or subtraction by 1. The increment
& decrement operators are ++,--Assume integer B holds 20 then:
Operato
Description Example
r
++ Increment — Increase the value of operand by 1 B++ gives 21
-- Decrement — Decrease the value of operand by 1 B—gives 19
Pre increment post increment:
++x; x++;
x=3; x=3
m==++x; m=x++;
m=4 m=3
x=4 x=4
6. Conditional Operator(or) ternary operator(? : ) Conditional operator is also known as the ternary
operator. Since this operator acts on 3-variables, it is called ternary operator.
Syntax:- variable =expression1 ? expression2:expression3;
This means, expression1 is evaluated first , if it is true then expression2 value is stored otherwise expression3
value is stored into variable.
7. Bitwise Operators: There are 7- bitwise operator in java. These operator acts on individual bit(0&1) of the
operands. They act on integer data types.
1) Complement operator (~):it given the complement from of given number by changing O's as 1’s and vice -
verse.
2) Bitwise and operator(&):-perform ‘and ‘operation form on the individual bits number.
E.g. - x=10=0000 1010
y=11=0000 1011
x&y = 0000 1010
3) Bitwise ‘or’ operator (|):- this operator perform ‘or’ operator on the bits of the number.
E.g. - x=10=0000 1010
Y=11=0000 1011
X|y = 0000 1011
4) Bitwise ‘xor’ operator(^):-this operator perform exclusive or ‘xor’ operation on the bits of the number.
when we have odd no. of is in the i/p bits ,we can get o/p bit as1.
Dot Operator(.): The dot(.) operator is used to access the instance variables and methods of class
object.
Ex: Person1.age; - refers to the variable age
Person1.salary(); - refers to the function salary()
It is also used to access class and sub – packages in a package.
Priority of operator:-
1) ( ) &[ ]
2) ++,--
3) *,/,%
4) +,-
5) Relational operator
6) Boolean bitwise operators
7) Logical operator
8) Ternary operator
9) Assignment operator (=).
if(n%2= =0)
{
System.out.println(“given number”);
}
}
}
ii. If-else Statement:The "if-else" statement is an extension of if statement .If test expression is true,true block
statements are executed otherwise false block statements are executed.In both cases control is transferred to
statement-x
Syntax:
if(test expression)
{
True-blockstatement(s);
}
else
{
False-block statement(s)
}
statement-x;
Example:
class Biggest
{
Public static void main(String args[])
{
int a=25,b=35;
if(a>b)
{
System.out.println(“a is big”+a);
}
else
{
System.out.println(“b is big”+b);
}
}
}
iii. Nested If-else Statement:when a series of decisions are involved, we may have to use more than one if…
else statement in nested form as follows:
Syntax: if(test condition1)
{
if(test condition2)
{
<statement1>;
}
else
{
<statement2>;
}
}
else
{
<statement3>;
}
statement-x;
Here if the condition1 is true then condition2 is checked. If condition2 is true the condition statements in
internal if block is executed otherwise statements in else block is executed.
If condition1 is false then statement in outer else block(statement3) is executed. After this control is transfer to
statement -x.
Example:
Class NestingIfStmt
{ Public static void main(String args[])
{
int a=25,b=35,c=20;
if(a>b)
{
if(a>c)
{
System.out.println(“a is big”+a);
}
else
{
System.out.println(“c is big”+c);
}
}
else
{
if(b>c)
{
System.out.println(“b is big”+b);
}
else
{
System.out.println(“c is big”+c);
}
}
}
}
iv. Else if ladder:There is another way of putting ifs together when multipath decisions are involved. A
multipath decision is a chain of ifs in which the statement associated with each else is an if.
Syntax: if(condition1)
{
<statement1>;
}
else if(condition 2)
{
<statement2>;
}
else if(condition 3)
{
<statement3>;
}
:
:
else
{
<statement default>;
}
statement-x;
Example:
class Ladder
{
public static void main(String args[])
{
int per=40;
if(per>=75)
{
System.out.println(“First class with distinction”);
}
else if(per>=60)
{
System.out.println(“First class”);
}
else if(per>=55)
{
System.out.println(“Second class”);
}
else if(per>=40)
{
System.out.println(“Third class”);
}
else
{
System.out.println(“Fail”);
}
}
}
2. Switch Statement:The keyword "switch" is followed by an expression that should evaluates to byte, short,
char or int primitive data types ,only. In a switch block there can be one or more labeled cases. The expression
that creates labels for the case must be unique. The switch expression is matched with each case label. Only the
matched case is executed , if no case matches then the default statement (if present) is executed.
Syntax: switch(expression)
{
case value-1:
block-1
break;
case value-2:
block-2
break;
...
...
default:
default-block
break;
}
statement-x;
Example:
import java.io.*;
import java.util.Scanner;
class SwitchStmt
{
public static void main(String args[])
{
int ch;
Scanner sc=new Scanner(System.in);
System.out.println(“Enter your choice ”);
ch=Integer.parseInt();
switch(ch)
{
case1:System.out.println("Sunday");
break;
case2:System.out.println("Monday");
break;
case3:System.out.println("Tuesday");
break;
case4:System.out.println("Wednesday");
break;
case5: System.out.println("Thursday");
break;
case6:System.out.println("Friday");
break;
case 7:System.out.println("Saturday");
break;
default:
System.out.println("Invalid");
}
}
}
class ForEachExample1{
public static void main(String args[]){
int arr[]={12,13,14,44};
for(int i:arr){
System.out.println(i);
}
}
}
10.
Output:12
13
14
44
2.15 Know the syntax of jump statements, break and continue statements
Branching Statements: Jump statements in java are used to transfer the control to another part of java
program. It supports 3 jump statements. They are
1. Break statement
2. Continue statement
3. Return statement
1. Break statement: The break statement can be used in 3-way:
Example: Here Welcome() function is called within println() function which returns a String value "Welcome
to roseIndia.net". This is printed to the screen.