java notes by prince

92
1 Amit Kumar How java program run :- To understand how java program run, we must understand about two new terms. These are Bytecode and Virtual machine (VM). Bytecode: - This code is actually platform independent. We can consider it as a machine code. When you compile an anyfile.java file successfully, you can get this code. It is in the form of anyname.class file. Virtual Machine:- The name virtual suggests that this is not an actual machine. It is just a program which simulates a machine on which java programs are supposed to run. Actually, you can suppose that is a hardware which runs programs in Bytecode. Fig shows the compilation process and interpreted stage. (Running a Java Program) Difference between Java Applets and Java Application :- We can use java for two types of programs, namely applets and applications. Applets are executed in (Java Enabled) web Browsers. Applets are like a small java program. It can be dynamically downloaded from the internet. Applications are programs similar to the ones that we find in any other languages. Since they do not need a browser, they are sometimes referred to as stand-alone application. Advantage of Java technology :- 1. Get started quickly: - Although the java programming language is a powerful object- oriented language, it’s easy to learn, especially for programmers already familiar with C or C++. 2. Write less code: - Comparisons of program metrics suggest that a program written in the java programming language can be four times than the same program in C++. 3. Write better code:- The java programming language encourages good coding practices, and its garbage collection helps you avoid memory leaks. Its object orientation, its java Beans component architecture, and its wide- ranging, easily extendible API let you reuse other people’s tested code and introduce fewer bugs. 4. Develop program faster:- Your development time may be as much as twice and fast versus writing the same program in C++. 5. Avoid platform independencies with 100% pure java:- You can keep your program portable by following the purity tips mentioned throughout this tutorial and avoiding the use of libraries written in other language. 6. Write once run anywhere:- Because 100% pure java programs are compiled into machine independent Bytecode, they run consistently on any java platform. Source Code Output Byte Code Java Compiler Java Interpreter

Upload: sandeep-parab

Post on 27-Jun-2015

91 views

Category:

Documents


8 download

TRANSCRIPT

How java program run :To understand how java program run, we must understand about two new terms. These are Bytecode and Virtual machine (VM). Bytecode: - This code is actually platform independent. We can consider it as a machine code. When you compile an anyfile.java file successfully, you can get this code. It is in the form of anyname.class file. Virtual Machine:- The name virtual suggests that this is not an actual machine. It is just a program which simulates a machine on which java programs are supposed to run. Actually, you can suppose that is a hardware which runs programs in Bytecode.

Source Code

Java Compiler

Byte Code

Java Interpreter

Output

Fig shows the compilation process and interpreted stage. (Running a Java Program)

Difference between Java Applets and Java Application :We can use java for two types of programs, namely applets and applications. Applets are executed in (Java Enabled) web Browsers. Applets are like a small java program. It can be dynamicallydownloaded from the internet. Applications are programs similar to the ones that we find in any other languages. Since they do not need a browser, they are sometimes referred to as stand-alone application.

Advantage of Java technology :1. Get started quickly: - Although the java programming language is a powerful objectoriented language, its easy to learn, especially for programmers already familiar with C or C++.

2. Write less code: - Comparisons of program metrics suggest that a program written in thejava programming language can be four times than the same program in C++. The java programming language encourages good coding practices, and its garbage collection helps you avoid memory leaks. Its object orientation, its java Beans component architecture, and its wide- ranging, easily extendible API let you reuse other peoples tested code and introduce fewer bugs.

3. Write better code:-

4. Develop program faster:- Your development time may be as much as twice and fastversus writing the same program in C++. You can keep your program portable by following the purity tips mentioned throughout this tutorial and avoiding the use of libraries written in other language. Because 100% pure java programs are compiled into machine independent Bytecode, they run consistently on any java platform.

5. Avoid platform independencies with 100% pure java:6. Write once run anywhere:-

1

Amit Kumar

7. Distribute software more easily:- You can upgrade applets easly from a central server.Applets take advantage of the feature of allowing new classes to be loaded on the fly, without recompiling the entire program.

Java Development Kit Tools :The JDK is a development environment for building applications, applets, and the components using the java programming language. In more technical terms, the current version is called Java TM Platform, Standard edition 6 JDK. The JDK 6 includes tools useful for developing and testing programs written in java. They help us to running them on the java platform. These tools are designed to be used from the command line. They do not provide a GUI. The only exception is the appletviewer. Let us describe the contents of JDK 6 in details. 1. Development tools :- Tools and utilities that will help one to develop, execute, debug, and document program written in the java programming language are provided in the bin subdirectory. These tools are the foundation of the JDK 6.The basic tools are describe in the given below: a. Javac The compiler of java programming language. b. Java The launcher for java applications. In this release, a single launcher used for both development and deployment. c. Javadoc API documentation generator. d. Appletviewer Run and debug applets without a web browser. e. Jar Manage java Archive (JAR) files. f. Jdb The java debugger. g. Javah C header and sub generator. used to write native methods. h. Javap Class file disassemble. 2. Runtime Environment :- An implementation of the java 2 runtime environment for use by the SDK. The runtime environment includes a JVM, Class libraries, and other files that support the execution of program written in the java programming language. These are present in jre sub directory. 3. Addition documentation:- Addition class libraries and support files required by the development tools are present in the lib sub directory. Etc.

2

Amit Kumar

Chapter-3

Java Language Basic

Java Program structure :public class { public static void main(String arg[]) { ; . ; } }

Example:- File Name- FirstJava.javapublic class FirstJava { public static void main(String arg[]) { System.out.println(This is my first java program); } } Compile and execute the program:C:\>javac FirstJava.java C:\>java FirstJava This is my first java program C:\>

Basic Building Block.Any java program consist of few building blocks like comments, declarations statements and methods. These blocks are formatted by some small atomic quantity is known as tokens.

Comments :- Comments are that part of the program, which are supported to give moreinformation to the reader. They increase the readability of the program. The compiler does not convert it in to code.(We may say that compiler ignore it.). In java, the comments are enclosed in pair of /* and */, such comments can be of one or more lines. In addition java uses double slash (//) for single line comments. Any text from // to be end of that line is treated as comment.

Variables & Data Types:Variable:Variable is a name location in memory which holds the constant. According to programming rule variable is an identifier. Hence, rule for formatting variables same as those for formatting identifiers. Rules for variable names can be started as follows: 1. Variable names are formatted with the help of letters and digits. 2. Alphabets can be in upper or lower case. 3. Only letters are allowed as far as string character. Underscore character (_) and Dollar ($) are treated as letter as far as variables re concerned. 3 Amit Kumar

4. The first character cannot be a digit. 5. There is no restriction on number of characters in variables. 6. As white space characters are used to separate tokens, they cannot be a part of variables.

Keywords in javaabstract assert Boolean break byte case catch char class const continue default do double else extends final finally float for goto if implements import instanceof int interface long native new package private protected public return short static strictfp super switch synchronized this throw throws transient try void volatile while

Data Types:- The Data that is stored in memory can be of many types for example a persons age isstore as a numeric value and an address is stored as alphanumeric characters. Data type are use to define the operations possible on them and the storage method. The data type in java is classified in two types:1. Primitive or slandered data type. 2. Abstract or derived data type.

1. Primitive or slandered data type.Primitive data type also known as standard data types, are the data types that are built into the java language. The java compiler contains details introduction on each legel option supported by the data type. There are eight data types in java i.s; I. byte 1 Byte (8 Bits). -128 to 127 II. short 2 Byte (16 Bits). -32768 to 32767 III. int 4 Byte (32 Bits). -2147473648 to 2147473647 IV. long 8 Byte (64 Bits). -9223372036854775808 to 9223372036854775807 V. float 4 Byte (32 Bits). -3.4E38 to +3.4E38 VI. double 8 Byte (64 Bits). -1.7E308 to +1.7E308 VII. char 2 Byte (16 Bits). VIII. boolean 2 Byte (16 Bits). NOTE :- Data is internally separated as binary digits (0 and 1).Bits stand for binary digit. A bit can store either 0 or 1.

2. Abstract or Derived data type.Abstract data types are base on primitive data type and have move functionality than primitive data type. For example String is an abstract data type. That can store letters digits and others character like /, (, ), :, ;, $, #,. The data type cannot perform calculations on a variable of a String data type even if the data stored in it has digits. However String provides methods for one String within another extracting the position of a string. The primitive data type does not have these features. 4 Amit Kumar

Conversions / Typecasting :- Java supports two type of conversion I.e. Widening conversion/Implicit conversion or Narrowing conversion/ Explicit conversion. 1. Widening Conversion :- Widening conversion(Implicit conversion) take place in java when the following condition make true. a. The source and target/destination type must be compatible. b. The target size / capacity must be greater than or equal to source size /capacity. Use:Variable=value/variable/expression;

Automatically / Implicitly

TargetExample:1. public class Wconversion1 { public static void main(String arg[]) { byte a,b; b=20; a=b; //Widening conversion. System.out.println(Value of a= +a); System.out.println(Value of b= +b); } } 2. public class Wconversion2 { public static void main(String arg[]) { byte a; int b; a=20; b=a; //Widening conversion. System.out.println(Value of a= +a); System.out.println(Value of b= +b); } }

Source-: Widening Conversion or Implicit Conversion:-

2. Narrowing Conversion(Explicit Conversion):- When target size/capacity is less than thesource size or capacity or when the source size is greater than the target size, and explicitly conversion required to assign value to smaller size using the syntax given below: Use:5 Amit Kumar

Target_type Variable= (Target_type) variable;

OrTarget_type variable= (Target_type)(Expression);

Explicitly

Target

Source

-: Narrowing Conversion or Explicit Conversion:When source is explicitly cast in to smaller type, the conversion involved is referred to as narrowing or explicit conversion. Example:1. public class Nconversion1 { public static void main(String arg[]) { byte a; int b=20; // a=b; //Error (Int valu cannot assign in byte type). a = (byte)b; //Narrowing Conversion. System.out.println(Value of a= +a); System.out.println(Value of b= +b); } } 2. public class Wconversion2 { public static void main(String arg[]) { byte a,b=10; // a=b*5; //Error (Int valu cannot assign in byte type). a= (byte)(b*5); System.out.println(Value of a= +a); System.out.println(Value of b= +b); } }

Automatically Type Promotion Rule:- Java Automatically promotes:a. b. All byte, short and char type in an expression to integer type. A float variable is initlised at the time of declaring variable to overcome this problem either use double data type or postfix the value with character f.

Example:6 Amit Kumar

1.

public class Aconversion1 { public static void main(String arg[]) { // float a=2.45 ; //Error (Double value cannot assign in float type). float a=2.45f; System.out.println(Value of a= +a); } }

How to create object in java:- An object in java is a combination of instancevariable(Attributes) and methods to work on instance variables, methods must be define and methods is the only way to access the instance variable and instance variable must be encapsulated. A class (Which define object type) in java is a logical frame work and object is physical reality. An object in java is always created dynamically (That is at run time) to create an object in java is a two step process as follows: Step 1:At first create object reference variable in the following format to hold internally the reference of allocated object. Syntax:

,,.;Step 2:Secondary create object using new operator in the following format and assign object reference variable to object reference variable. Syntax:

= new ( ); Note:- Class name is same as class name of first step. These two steps can be combined in to one.Syntax:

= new ( ); Note:- An object in java is cannot be of primitive.

Console input in Java :Java provides a package named IO which contains two important classes named BufferedReader and InputStreamReader which is responsible to accept input from standard input device I,e; keyboard. 7 Amit Kumar

In order to create object of these classes to read date from console input iopackage must required to be explicitly import in the user program.

import java.io.*; To accept input from standard input device follow the following steps:Step1:- At first create BufferedReader object in the following format.

BufferedReader =new BufferedReader(new InputStreamReader(System.in));Step 2:- Read the data in the local variables using BufferedReader method readLine() in the following format. =.readLine(); Note:- readLine() converts the data in to the String. String in java is an object of class String.

Convert String to Numeric type:At the time of accepting value through keyboard we will change the String type value in the numeric type. We will use the following methods: =.valueOf(.readLine()).num_typeValue(); Example1:import java.io.*; public class InputTest1 { public static void main(String arg[])throws IOException { BufferedReader obj=new BuggeredReader(new InputStreamReader(System.in)); String str1; System.out.println(Enter a string); Str1=obj.readLine(); System.out.println(Inputed String is + str1); } }

Example2:import java.io.*; 8 Amit Kumar

public class InputTest2 { public static void main(String arg[])throws IOException { BufferedReader obj=new BuggeredReader(new InputStreamReader(System.in)); int num; System.out.println(Enter a number); Num=Integer.valueOf(obj.readLine()).intValue(); System.out.println(Inputed number is +num); } } Note:- At the time of input with the help of standard input device i.e; keyboard a exception will be raised, which exception is known as IOException that is handle by the system with the help of throws keyboard.

-:Operators:Operators perform operations on operands. Operands may be one two or three. Operands are either variables or constants. The operators, which take single operand are called unary operators. Those takes two operands are known as binary operators and one having three operands is known as ternary operator. Most of the operators are binary operators, few are unary while there is only one ternary operator (for example ?: operator). Arithmetic operators. Assignment operators. Relational operators. Logical operators. Unary operators. Bitwise operators. Others operators.

1. Arithmetic operators:+ * / % (Addition) (Subtraction) (Multiplication) (Division) (Modulo Division)(Remainder)

Note :1. When the use of plush (+) operator use with numeric operands, the result is numeric when both the operands are Strings the plush operator concatenates (joins) then when one of the operands is a String objects, the second operand is converted in to String before concatenation. 9 Amit Kumar

Example:-

Operend1

+

Operend2

=

Result

5 6 11 5 ABC 5ABC ABC 5 ABC5 ABC XYZ ABCXYZ 2. Java use toString() method of java.lang.object class to convert data to the String Data Type. Example1:import java.io.*; public class ArithmeticOperator { public static void main(String arg[])throws IOException { BufferedReader obj=new BuggeredReader(new InputStreamReader(System.in)); int rad; float circlearea,pi=3.14f; System.out.println(Enter a radius of circle); rad=Integer.valueOf(obj.readLine()).intValue(); circlearea=pi*rad*rad; System.out.println(Area of circle is +circlearea); } }

2. Assignment Operator :We have seen equal to (=) is a basic assignment operator. It assigns value on right hand side to variable on left hand side.

Var = ;Example:Marks=90; Note:To handle such situation java provides some shortcut assignment operator, with the combination of arithmetic operator and assignment operator. i.e; += Assign Sum a+=20; a=a+20; -= Assign Difference a-=20; a=a-20; *= Assign Product a*=20; a=a*20; /= Assign Quotient a/=20; a=a/20; %= Assign Remainder a%=20; a=a%20;

3. Relational Operator :When we use relational operator in an expression it returns Boolean Value true or false. Java provides these relational operators. 10 Amit Kumar

< >= == !=

Less than less than or equal to Greater than Greater than or equal to Equal to Not equal to

4. Logical Operator :The logical operator combines the result of Boolean expressions. The following logical operators used in java are:

&&(Logical And) :Evaluates to true if both the conditions evaluate to true, false if otherwise. Example X=5; Y=10; x>=5 x>=5 x5 && && && && y==10 y>10 y==10 y=5 || y==10 true x>=5 || y>10 true x5 || y10) false true

5. Unary Operator :Java support basically two unary operator. I.e;

++ :Increase the value of the operand by one. 11 Amit Kumar

Ex:X=10; X++; ++X X=11; X=11;

-- :Decrease the value of the operand by one. Ex:X=10; X--; --X X=9; X=9;

Note: - Increment (++) and Decrement (--) operator is used as postfix and prefix order. If it is used aspostfix then first drop the value of operand first after that performs the job of operator. And in case of prefix first perform the job of operator and lastly drop the value of operands.

6. Bitwise Operator :Those types of operator which perform own job upon the smallest unit of memory (Bits) is known as bitwise operators. Java supports following bitwise operators: 1. 2. 3. 4. 5. 6. & | ^ ~ >> z)?y:z; X is assigned the value of y if y is greater than z else x is assigned the value of z.

2. New Operator:When user creates an instance of a class, user needs to allocate memory for it. When user declares an object, user merely states its data type.

Syntax12 Amit Kumar

Class name object_ref_variable=new Class Name(); Or Class name object_ref_var1,Object_ref_var2,; Object_ref_var1=new Class name();

Order of precedence of operatorOperator Precedence Group1. (), [], Postfix ++, Postfix -2. Unary +, Unary-, Prefix ++, Prefix--, ~, ! 3. (type), new 4. *, /, % 5. +, 6. , >>> 7. = 8. ==, != 9. & 10. | 11. && 12. || 13. ?: 14. =, +=, -=, *=, /=, %=, =, >>>=, &=, |=, ^=

AssociativityLeft Right Left Left Left Left Left Left Left Left Left Left Left Right

Final Keyword:The variables are for holding different values at different times. If we want to keep a value constant, we may declare a variable as final. Such a variable has initialized only once. final var=value; Example:final int num=30;

-: Control Statement:Java supports three type of control statement for controlling the set of statements. These are: 1. Selection Statement 2. Looping Statement 13 Amit Kumar

3. Jump Statement

1. Selection Statement :Java supports two type of selection statement, if and switch. These statements allow controlling the flow of our programs execution based upon conditions known only during run time. (a)

if construct:-

The if decision construct is followed by a logical expression in which data is compared and decision is made based on the result of the comparison.

Syntaxif() { ; } else { ; } Example: public class IfElse1 { public static void main(String arg[]) { int x=20; int y=30; if(x>y) { System.out.println(X is greater than Y); } else { System.out.println(Y is greater than X); } } } (b) Nested if construct:14 Amit Kumar

A nested if is an if statement that is the target of another if or else. Nested if is very common in programming.

Syntaxif() { ; if() { ; } else { ; } } else { ; if() { ; } } Example: public class IfElse2 { public static void main(String arg[]) { int x=20; int y=30; int z=40; if(x>y) { if(x>z) { System.out.println(X is greater); } else { if(z>y) 15 Amit Kumar

{ System.out.println(Z is greater); } } } else { if(y>z) { System.out.println(Y is greater); } else { System.out.println(Z is greater ); } } } } (c) If-else-if construct:Java supports an else-if word. By using it we will check the condition in option part of our conditional statement.

Syntaxif() { ; else if() { ; } else if() { ; } else { ; } Example: public class IfElseIf1 { public static void main(String arg[]) 16 Amit Kumar

{ int x=20; int y=30; int z=40; if(x>y&&x>z) { System.out.println(X is greater); } else if(y>x&&y>z) { System.out.println(Y is greater); } else { System.out.println(Z is greater ); } } } (d) Switch case:Switch case structure is used to execute sequence of statements based on selection specified with case statements.

Syntaxswitch (choice) { case 1: ; break; case 2: ; break; case 3: ; break; default: ; }

Note:

Only constraint numeric and character value are allowed with case statements. Variable or expression is allowed within the parenthesis of switch case. Default is optional and can be used if required. Break within switch can be used to break the control of execution and continue on resume it just very next close curly braces encountered. The switch case is internally working on numeric constant. 17 Amit Kumar

Maximum of 33 switch structure can be a target of another switch. Example import java.io.*; public class SwitchCase { public static void main(String arg[])throws IOException { BufferedReader obj=new BuggeredReader(new InputStreamReader(System.in)); int dno; System.out.println(Enter day Number); dno=Integer.valueOf(obj.readLine()).intValue(); switch(dno) { case 1: System.out.println(SunDay); break; case 2: System.out.println(MonDay); break; case 3: System.out.println(TuesDay); break; case 4: System.out.println(WedDay); break; .. case 7: System.out.println(SaturDay); break; default : System.out.println(Invalid Day Number); break; } } }

18

Amit Kumar

2. Looping Statement :A loop causes a section of a program to be repeated a certain number of times. The repetition continues while the condition becomes false. The loop ends and the control are passed to the statement following the loop. Java support three looping constructs While loop Do while loop For loop

While loop:The while statement continually executes a block of statements while a particular condition is true. Its syntax can be expressed as:

Syntaxwhile (expression) { ; < Increment /Decrement>; } NOTE: The while statement evaluates expression, which must return a Boolean value. If the expression evaluates to true, the while statement executes the set of statement(s) in the while block. The while statement continues testing the expression and executing its block until the expression evaluates to false.

Increment/ Decrement statement is required to break the loop in certain period. If no Increment/ Decrement statement is found in the body of loop, the loop becomes infinite. Example public class WhileDemo { public static void main(String[] args) { int count = 1; while (count < 11) { System.out.println("Count is: " + count); count++; } } } 19 Amit Kumar

DoWhile loop:-

In some conditions in java, you need to run some statements and processes once at least. For that you have to use the do while loop in after that check the condition then we use the dowhile loop statement. do-while loop is same as the while loop statement but while loop checks the certain condition is first and if condition is true then statements or processes are executed otherwise all the statements written under the while loop is ignored by the interpreter but do - while loop executes all the statements first at once and then check the condition if the condition is true then all the statements are also executed in second times otherwise second times ignored all the statements.

Syntaxdo { ; < Increment /Decrement>; }while(condition); NOTE: In a dowhile structure the condition is checked at the end /bottom so, if very first time condition is false, the loop body executed at the last one time. The dowhile loop is basically used for menu driven programming. The condition terminated by semicolon.

Example public class DoWhile { public static void main(String[] args) { int n = 12345; int t,r = 0; System.out.println("The original number : " + n); do { t = n % 10; r = r * 10 + t; n = n / 10; }while (n > 0); System.out.println("The reverse number : " + r); } }

20

Amit Kumar

For loop:-

The for statement provides a compact way to iterate over a range of values. Programmers often refer to it as the "for loop" because of the way in which it repeatedly loops until a particular condition is satisfied.

Syntaxfor (initialization; termination; increment) { ; }

NOTE:

The initialization expression initializes the loop; it's executed once, as the loop begins. When the termination expression evaluates to false, the loop terminates. The increment expression is invoked after each iteration through the loop; it is perfectly acceptable for this expression to increment or decrement a value.

Example public class ForDemo { public static void main(String[] args) { for(int i=1; i