EASY TO LEARN:-JAVA (Beginners) How to learn JAVA This course describe the Core java and syntax of java programming language. Course cover the object –oriented concepts as they apply to the java programming language. While the java programming language is operating system-independent, the GUI that it prodyce can be dependent on the operationg system on which code is executed. In this course, program are run in the Microsoft Windows operating environment.
anurag RANA UNIVERSITY INSTITUTE OF INFORMATION TECHNOLOGY HIMACHAL PRADESH UNIVERSITY SHIMLA-5
ACKENOWLEDGEMENTS The Author is grateful to God, his parents, teachers and students(UIIT Batch 2010-14). Writing this requires sincere efforts, hardwork and blessings of omnipresent God and other who motivated me to write. anurag RANA
OVERVIEW INTERNET TECHNOLOGY (CORE JAVA)
CORE JAVA 1. Introduction 2. Data Types 3. Operators 4. Control Statements 5. Introduction to Class 6. Classes and Methods 7. Inheritance 8. Interfaces 9. Packages 10.
Wrapper Class
11. String & StringBuffer 12.
Exception Handling
13.
Multithread INTERNET TECHNOLOGY (CORE JAVA)
CONTENTS 1.Introduction a. b. c. d.
History Features of Java Tokens Java Literals
2.Data Types a. b. c. d.
Introduction What is data type? Variables Array
3.Operators a. b. c. d. e. f. g.
Introduction to operator Arithmetic operators Bitwise Operators Relational Operators Boolean Logical Operators Assignment Operator The ? Operator
4.Control Statements a. Selection Statements b. If selection statements c. Switch selection statement INTERNET TECHNOLOGY (CORE JAVA)
d. Looping statements e. Jump Statements
5.Introduction to Class a. b. c. d. e. f.
What is class? Declaring Objects Introduction to method Constructor Keywords Access Control
6.Classes and Methods a. b. c. d. e. f. g. h.
Method overloading Constructor overloading More about method Call by value Call by reference Recursion Nested class Command Line Argument
7.Inheritance a. b. c. d. e. f. g. h.
Inheritance Super & final Method overriding Multilevel Inheritance Dynamic Method Dispatch Abstract Classes Object Class Polymorphism
8.Interfaces a. b. c. d. e.
Introduction Defining interfaces Implementing interfaces Interface variables Extending interfaces
9.Packages INTERNET TECHNOLOGY (CORE JAVA)
a. b. c. d. e. f. g.
Introduction Vector class Random class Date class Calendar & Gregorian class Math Class Hashtable
10. Wrapper Class a. b. c. d. e. f. g. h. i.
Introduction Byte Short Integer Long Double Float Character Boolean
11. String & StringBuffer a. String Handling b. Methods & Examples c. StringBuffer
12. Exception Handling a. b. c. d. e.
Introduction Try and catch Finally Throw Throws
13.Multithreading a. b. c. d. e.
Introduction to thread The Main Thread Thread Life Cycle Creating Thread Thread Priority INTERNET TECHNOLOGY (CORE JAVA)
INTERNET TECHNOLOGY (CORE JAVA)
CORE JAVA History of java: In 1991, Sun Microsystems was attempting to develop a new technology for programming next generation smart appliances. The original plan was for the Star7 operating system to be developed in C++ but rejected the idea for several reasons. As a result we have new language that was better for the purposes of the Green project than C++ developed by Gosling. He called the language Oak in honor of a tree that could be seen from his office window. James Gosling was part of Green, an isolated research project at Sun that was studying how to put computers into everyday household items like thoughtful toasters, sagacious Salad Shooters and lucid lamps. The group also wanted these devices to communicate with each other. In January 1995, The meeting, arranged by Kim Polese (marketing person) where about a dozen people got together to brainstorm with James Gosling, a vice president and fellow of Sun, and the author of Oak, the final suggest names were Silk, DNA, Ruby, WRL and Java by the team in meeting But the other names could not trademark. So finally JAVA was the name chosen because it sounded the coolest and decided to go ahead with it and name was first suggested by Chris Warth.
Features of Java: Object-oriented Java support the all the features of object oriented programming language such as Abstraction, Encapsulation, Inheritance, Polymorphism and Dynamic binding etc. So with the help of these features user can reduce the complexity of the program develops in JAVA. Java gave a clean, usable, realistic approach to objects so we can say that the object model in Java is simple and easy to extend. Platform Independent / Portable Java makes it possible to have the assurance that any result on one computer with Java can be replicated on another. So the code is run in the different platform has a same result. Simple and Powerful Java inherits the C/C++ syntax and many of the object-oriented features of C++.so we can say that Java was designed to be easy to learn and use. java provides a small number of clear ways to achieve a given task. Unlike other programming systems that they provide dozens of complicated ways to perform a simple task. Secure Java Compatible Browser, anyone can safely download Java applets without the fear of viral infection or malicious intent because of its key design principle. So anyone can download applets with confidence that no harm will be done and no security will be violated. Java achieves this protection by confining a Java program to the Java execution environment and by making it inaccessible to other parts of the computer. Robust Most programs in use today fail for one of the two reasons: (i) MEMORY MANAGEMENT MISTAKES For example, in C/C++, the programmer must manually allocate and free all dynamic memory. This sometimes leads to problems, because programmers will either forget to free memory that has been previously allocated or, sometimes try to free some memory that another part of their code is still using. Java virtually eliminates these problems by managing memory allocation (with the help of new operator) and deallocation. (deallocation is completely automatic, because Java provides garbage collection for unused objects.) (ii) MISHANDLED EXCEPTIONAL CONDITIONS
INTERNET TECHNOLOGY (CORE JAVA)
With the help of Exception Handling (try……….catch block), the programmer can easily handle an error or exception so user can prevent the program by automatically stop the execution when an exception found. Thus, the ability to create robust programs was given a high priority in the design of Java. Multithreaded Java supports programming, which allows the user to write programs that perform many functions simultaneously. The two or more part of the program can run concurrently then each part of such a program is called a Thread and this type of programming is called multithreaded programming. Each thread defines a separate path of execution. Thus, multithreading is a specialized form of multitasking. Architecture-neutral The Java designers worked hard in achieving their goal ―write once; run anywhere, anytime, forever‖ and as a result the Java Virtual Machine was developed. Java is Architecture-neutral it generates bytecode that resembles machine code, and are not specific to any processor. Interpreted and High performance The source code is first compile and generates the code into an intermediate representation called Java bytecode which is a highly optimized set of instruction code. This code can be interpreted on any system that has a Java Virtual Machine and generates the machine code. Java bytecode was carefully designed by using a just-in-time compiler so that it can be easily translated into native machine code for very high performance. Most of the earlier cross-platform solutions are run at the expense of performance. Distributed Java allows the object can access the information across the network with the help of RMI (Remote Method Invocation) means this allowed objects on two different computers to execute procedures remotely. So this feature supports the client/server programming. Dynamic Java programs carry with them substantial amounts of run-time type information that is used to verify and resolve accesses to objects at run time. This makes it possible to dynamically link code in a safe and perfect manner.
Token: A token is the smallest element of a program that is meaningful to the compiler. (Actually, this definition is true for all compilers, not just the Java compiler.) These tokens define the structure of the Java language. When you submit a Java program to the Java compiler, the compiler parses the text and extracts individual tokens. Java tokens can be broken into five categories: identifiers, keywords, literals, operators, and separators. The Java compiler also recognizes and subsequently removes comments and whitespaces.
Identifiers : Identifiers are tokens that represent names. These names can be assigned to variables, methods, and classes to uniquely identify them to the compiler. ―Identifiers means a sequence of uppercase(A,B,C,……,Y,Z) and lowercase(a,b,c,…..,y,z) letters, numbers(0,1 ,2,……,9), or the underscore(_) and dollar-sign($) characters and must not begin with a number.‖ Valid and invalid Java identifiers. Valid HelloWorld Hi_JAVA
Invalid Hello World (uses a space) Hi JAVA! (uses a space and punctuation mark)
INTERNET TECHNOLOGY (CORE JAVA)
value3 3value(begins with a number) Tall short (this is a Java keyword) $age #age (does not begin with any other symbol except _ $ ) NOTE : For Java identifiers, you should follow a few stylistic rules to make Java programming easier and more consistent. It is standard Java practice to name multiple-word identifiers in lowercase except for the beginning letter of words in the middle of the name. For example, the variable firstValue is in correct Java style; the variables firstvalue, FirstValue, and FIRSTVALUE are all in violation of this style rule. Another more critical naming issue regards the use of underscore and dollar-sign characters at the beginning of identifier names. Using either of these characters at the beginning of identifier names is a little risky because many C libraries use the same naming convention for libraries, which can be imported into your Java code. A good use of the underscore character is to use it to separate words where you normally would use a space (Hi_JAVA).
Keywords : ―It is a special type of reserved word for a specific purpose which cannot be use as a identifier means cannot be used as names for a variable, class, or method.‖ There are 49 reserved keywords currently defined in the Java language (see the following table). abstract assert boolean break byte case catch char class const continue default do
double else extends false final finally float for goto if implements import instanceof
int interface long native new package private protected public return short static super
switch synchronized this throw transient true try void volatile while
The keywords const and goto are reserved but not used. In the early days of Java,several other keywords were reserved for possible future use. In addition to the keywords, Java reserves the following: true, false, and null. These are values defined by Java. You may not use these words for the names of variables, classes, and so on.
Separators : Separators are used to inform the Java compiler of how things are grouped in the code. For example, items in a list are separated by commas much like lists of items in a sentence. The most commonly used separator in Java is the semicolon. As you have seen, it is used to terminate statements. Symbol ;
Name Semicolon
,
Comma
Purpose Terminates statements. Separates consecutive identifiers in a variable
INTERNET TECHNOLOGY (CORE JAVA)
declaration. Also used to chain statements together inside a for statement. Used to contain the values of automatically initialized arrays. {}
Braces
()
Parentheses
Also used to define a block of code, for classes, methods, and local scopes. Used to contain lists of parameters in method definition and invocation. Also used for defining precedence in expressions, containing expressions in control statements. Also used for surrounding cast types. Used to declare array types.
[] .
Brackets Period
Also used when dereferencing array values. Used to separate package names from subpackages and classes Also used to separate a variable or method from a reference variable.
Comments and Whitespaces : The comments and whitespaces are removed by the Java compiler during the tokenization of the source code. White space consists of spaces, tabs, and linefeeds. All occurrences of spaces, tabs, or linefeeds are removed by the Java compiler, as are comments. Comments can be defined in three different ways, as shown in Table. Types of comments supported by Java. Type
Syntax // Single-line comment /* comment Multiline */ /** Documentation comment */
Usage Example All characters after the // up to the end of the line //This is a Single-line style are ignored. comment. All characters between /* and */ are ignored.
/* This is a Multiline style comment.
Same as /* */, except that the comment can be used /** This is a javadoc style with the javadoc tool to create automatic comment. */ documentation.
Literals : A constant value in Java is created by using a literal representation of it. For example, Here are some literals : integer literal value : 100 floating-point literal value : 98.6 character literal value : ‗X‘ string literal value : ―This is a test‖ A literal can be used anywhere a value of its type is allowed.
Integer Literals : Integer literals are the primary literals used in Java programming. They come in a few different formats: decimal, hexadecimal, and octal. These formats correspond to the base of the number
INTERNET TECHNOLOGY (CORE JAVA)
system used by the literal. Decimal (base 10) literals appear as ordinary numbers with no special notation. Hexadecimal numbers (base 16) appear with a leading 0x or 0X. Octal (base 8) numbers appear with a leading 0 in front of the digits. For example, an integer literal for the decimal number 12 is represented in Java as 12 in decimal, 0xC in hexadecimal, and 014 in octal. Integer literals default to being stored in the int type, which is a signed 32bit value. If you are working with very large numbers, you can force an integer literal to be stored in the long type by appending an l or L to the end of the number, as in 79L. The long type is a signed 64-bit value.
Floating-Point Literals : Floating-point literals represent decimal numbers with fractional parts, such as They can be expressed in either standard or scientific notation, meaning that the number 143.85 also can be expressed as 1.4385e2. Unlike integer literals, floating-point literals default to the double type, which is a 64-bit value. You have the option of using the smaller 32-bit float type if you know the full 64 bits are not required. You do this by appending an f or F to the end of the number, as in 5.6384e2f. 3.1415.
Boolean Literals : Boolean literals are certainly welcome if you are coming from the world of C/C++. In C, there is no boolean type, and therefore no boolean literals. The boolean values true and false are represented by the integer values 1 and 0. Java fixes this problem by providing a boolean type with two possible states: true and false. Not surprisingly, these states are represented in the Java language by the keywords true and false. Boolean literals are used in Java programming about as often as integer literals because they are present in almost every type of control structure. Any time you need to represent a condition or state with two possible values, a boolean is what you need. The two boolean literal values: true and false.
Character Literals : Character literals represent a single Unicode character and appear within a pair of single quotation marks. Special characters (control characters and characters that cannot be printed) are represented by a backslash (\) followed by the character code. Example of a special character is \n, which forces the output to a new line when printed. Table shows the special characters supported by Java. Description Representation \\ Backslash \ Continuation \b Backspace \r Carriage return \f Form feed \t Horizontal tab \n Newline \' Single quote \" Double quote \udddd Unicode character \ddd Octal character An example of a Unicode character literal is \u0048, which is a hexadecimal representation of the character H. This same character is represented in octal as \110.
String Literals : INTERNET TECHNOLOGY (CORE JAVA)
String literals represent multiple characters and appear within a pair of double quotation marks. String literals are implemented in Java by the String class. This arrangement is very different from the C/C++ representation of strings as an array of characters. When Java encounters a string literal, it creates an instance of the String class and sets its state to the characters appearing within the double quotes.
Operators: Operators means specify an evaluation to be performed on a data (Operands).
First Java program : Demonstrating program that displays the text,‖ Hello Java World! First JAVA program.....‖ on the console. public class FirstProg { //This is a first java program. public static void main(String[] args) { System.out.println("Hello Java World! First JAVA program....."); } }
Explanation : public : A keyword of the Java language that indicates that the element that follows should be made available to other Java elements. Public keyword indicates that the FirstProg class is a public class, which means other classes can use it. class : Java keyword that indicates that the element being defined here is a class. All Java programs are made up of one or more classes. A class definition contains code that defines the behavior of the objects created and used by the program.
FirstProg : An identifier that provides the name for the class being defined here. While keywords, such as public and class, are words that are defined by the Java programming language, identifiers are words that you create to provide names for various elements you use in your program. In this program, the identifier FirstProg provides a name for the public class being defined here. {: The opening brace marks the beginning of the body of the class. The end of the body is marked by the closing brace. Everything that appears within these braces belongs to the class. As you work with Java, you‘ll find that it uses these braces a lot. //This is a first java program. : This is a comment. Like most other programming languages, Java lets you enter a remark into a program‘s source file. The contents of a comment are ignored by the compiler. Instead, a comment describes or explains the operation of the program to anyone who is reading its source code. In this case, the comment describes the program and reminds you that the source file should be called FirstProg.java. Of course, in real applications, comments generally explain how some part of the program works or what a specific feature does. public : The public keyword is used again, this time to indicate that a method being declared here should have public access. That means classes other than the FirstProg class can use it. All Java programs must have at least one class that declares a public method named main. The main method contains the statements that are executed when you run the program. static :
INTERNET TECHNOLOGY (CORE JAVA)
Execute any elements (properties) without an object means before the object creating then it must declare a static so compiler directly execute those static elements.Here the main method is executed before the any object is creating so it must declare a static. The keyword static allows main( ) to be called without having to instantiate a particular instance of the class. This is necessary since main( ) is called by the Java interpreter before any objects are made. Java language requires that you specify static when you declare the main method. void : In Java, a method is a unit of code that can calculate and return a value. main : Identifier that provides the name for this method. Java requires that this method be named main because main( ) is the method called when a Java application begins. Besides the main method, you can also create additional methods with whatever names you want to use. (String[] args) : It‘s called a parameter list, and it‘s used to pass data to a method. Java requires that the main method must receive a single parameter that‘s an array of String objects. By convention, this parameter is named args. If you don‘t know what a parameter, a String, or an array is, don‘t worry about it You have to write (String[] args) on the declaration for the main methods in all your programs. In this case, args receives any command-line arguments present when the program is executed. This program does not make use of this information. System.out.println(“Hello Java World! First JAVA program..........”); : Statement in the entire program. It calls a method named println that belongs to the System.out object. System is a predefined class, it is automatically included in your programs that provides access to the system and out is the output stream that is connected to the console. The println method displays a line of text on the console. The text to be displayed is passed to the println method as a parameter in parentheses following the word println. In this case, the text is the string literal Hello Java World! First JAVA program................ enclosed in a set of double quotation marks. As a result, this statement displays the text on the console. Note: In Java, statements end with a semicolon. Because this is the only statement in the program, this line is the only one that requires a semicolon. Java is case-sensitive. Thus, Main is different from main. javac FirstProg.java This command creates a class file named FirstProg.class that contains the Java bytecodes compiled for the FirstProg class. Now run the program by entering this command: java FirstProg Output : Hello Java World! First JAVA program................
DATA TYPE IN JAVA Data types in java: For storing different type of data we have data types. Java defines eight types of data: byte, short, int, long, float, double, char and boolean. Integers:This group includes byte, short, int, and long, which are for signed and unsigned number
including zero.
INTERNET TECHNOLOGY (CORE JAVA)
Floating-point numbers:This group includes float and double, which can store numbers with fractional precision. Characters:This group includes char, which represents symbols in a characterset, like letters and numbers. Boolean:This group includes boolean, which is a special type for representing true/false values.
NOTE: The data types mentioned above are primitive data types. Java also support reference data types like Array, Class and Interface.
1. Integers: Java defines four integer types: byte, short, int, and long. All of these can have signed unsigned or zero value. Java does not support unsigned, positive-only integers. Name Width (in bits)
Range
long
64
–9,223,372,036,854,775,808 to 9,223,372,036,854,775,807
int
32
–2,147,483,648 to 2,147,483,647
short
16
–32,768 to 32,767
byte
08
–128 to 127
Note: Divide width with 8 to get size in Bytes; the table mentioned above is providing width and range of the integer data type. Width is the size the data type will occupy in the program if you write int a,b; than a and b both will occupy 32 bits (4 bytes) in memory.
1.1 byte The smallest integer type is byte. This is a signed 8-bit type that has a range from –128 to 127 Exp. byte b1; Variables of type byte are especially useful when we‘re working with a stream of data from a network or file.
1.2 short Short is a signed 16-bit type. It has a range from –32,768 to 32,767 so if you are sure that your value will not more than the range of Short data type than and only we recommended to use this. Exp short s1,s2;
1.3 int The most commonly used integer type is int. It is a signed 32-bit type that has a range from – 2,147,483,648 to 2,147,483,647. Exp. int a, b;
1.4 long long is a signed 64-bit type and is useful for those occasions where an int type is not large enough to hold the desired value. The range of a long is quite large. This makes it useful when big, whole numbers are needed.
Prog.No.:- 1 //Demonstrate the integer data type public class ITesst { public static void main(String[] args)
INTERNET TECHNOLOGY (CORE JAVA)
{ byte b1=50,b2=0; //declare short s1=10,s2=20; //declare and int i1=-555,i2=123; //declare and long l1=100000,l2=2033; //declare
and define define the define the and define
the byte variable short variable int variable the long variable
System.out.print("The value of different variables"); System.out.println(" of type integers is........."); System.out.println("byte integers : " + "b1 = " +b1 +" and b2 = " +b2); System.out.println("short integers : " + "s1 = " +s1 +" and s2 = " +s2); System.out.println("int integers : " + "i1 = " +i1 +" and i2 = " +i2); System.out.println("long integers : " + "l1 = " +l1 +" and l2 = " +l2); } } Output : C:\java> javac ITest.java C:\java> java ITest The value of different variables of type integers is......... byte integers : b1 = 50 and b2 = 0 short integers : s1 = 10 and s2 = 20 int integers : i1 = -555 and i2 = 123 long integers : l1 = 100000 and l2 = 2033
2. Floating-Point Types: Floating-point numbers, also known as real numbers, are used when evaluating expressions that require fractional precision. For example, calculations such as square root, or transcendental such as sine and cosine, result in a value whose precision requires a floating-point type. Name Width in Bits Approximate Range double 64 4.9e–324 to 1.8e+308 float 32 1.4e-045 to 3.4e+038
2.1 float Float specifies a single-precision value that uses 32 bits of storage. Single precision is faster on some processors and takes half as much space as double precision, but will become imprecise when the values are either very large or very small. When you require to store floating point value use float and double. Ex. float r, pi;
2.2 double Double precision, as denoted by the double keyword, uses 64 bits to store a value. Double precision is actually faster than single precision on some modern processors that have been optimized for high-speed mathematical calculations.
Prog.No.:- 2 //Demonstrate floating point data type. public class FTest { public static void main(String[] args) {
INTERNET TECHNOLOGY (CORE JAVA)
float f1=1.2f,f2=123.2f; //declare and define the float variable double d1=1.234,d2=23.4512; //declare and define the double variable System.out.print("The value of different variables"); System.out.println(" of type floating point is........"); System.out.println("float value : " + "f1 = " +f1 +" and f2 = " +f2); System.out.println("double value : " + "d1 = " +d1 +" and d2 = " +d2); } } Output : C:\java> javac FTest.java C:\java> java FTest The value of different variables of type floating point is........ float value : f1 = 1.2 and f2 = 123.2 double value : d1 = 1.234 and d2 = 23.4512
3. Characters: Data type used to store characters is char. NOTE: However, C/C++ programmers beware: char in Java is not the same as char in C or C++. In C/C++, char is an integer type that is 8 bits wide. This is not the case in Java. Java uses Unicode to represent characters. Unicode defines a fully international character set that can represent all of the characters found in all human languages. In Java char require 16-bit. The range of a char is 0 to 65,536. There are no negative chars. The standard set of characters known as ASCII still ranges from 0 to 127. The extended 8- bit character set, ISO-Latin-1, ranges from 0 to 255. Since Java is designed to allow applets to be written for worldwide use, it makes sense that it would use Unicode to represent characters.
Prog.No.:- 3 //Demonstrate char data type. public class CharTest { public static void main(String[] args) { char ch1, ch2; // declare the char variable ch1 = 88; // code for X ch2 = 'Y'; // define the char variable System.out.print("The value of type"); System.out.println(" character variable is........"); System.out.print("char data type : ch1 = "+ ch1 +" and ch2 = } }
"+ch2);
Output : C:\java> javac CharTest.java C:\java> java CharTest The value of type character variable is........ char data type : ch1 = X and ch2 = Y
4. Boolean: Java has a simple type, called boolean, for logical values. It can have only one of two possible values, true or false. This is the type returned by all relational operators, such as a < b. Exp. boolean b; So here the value of b is either true or false.
Prog.No.:- 4 //Demonstrate boolean data type. public class BoolTest { public static void main(String[] args)
INTERNET TECHNOLOGY (CORE JAVA)
{ boolean b; //declare the boolean variable b = false; //define the boolean variable System.out.print("The value of type"); System.out.println(" boolean variable is........"); System.out.println("boolean data type : b is " + b); b = true; //define the boolean variable System.out.println("boolean data type : b is " + b); // a boolean value can control the if statement if(b) System.out.println("This is executed."); b = false; if(b) System.out.println("This is not executed."); // outcome of a relational operator is a boolean value System.out.println("100 > 9 is " + (10 > 9));
//never execute
} } Output : C:\java> javac BoolTest.java C:\java> java BoolTest The value of type boolean variable is........ boolean data type : b is false boolean data type : b is true This is executed. 100 > 9 is true
VARIABLES IN JAVA The variable is the basic unit of storage in a Java program. A variable is defined by the combination of a type, an identifier and an optional initialize. Type is a data type or the name of a class or interface (class and interface will discussed further).for identify the type of variable identifier is a variable name and optional initializer means users directly initialize the value to the variable if they want.
Declare Variable Syntax for declaring a variable is... type identifier1=val , identifier2; Exp. int a=100, b; //initialize a and declare b. byte z = 22; // initialize z. double pi = 3.14159; // declares an approximation of pi. char x = 'x'; // the variable x has the value 'x'. Dynamic Initialization
Java allows variables to be initialized dynamically.
Prog.No.:- 5 public class VariableTest { public static void main(String[] args) {
INTERNET TECHNOLOGY (CORE JAVA)
int l = 10; int b = 20; int a;
a = l * b; System.out.println("normal initaialization : area is = "+a);
int area = l * b;
// it’s a dynamic initialization of variable name area
System.out.println("dynamic initaialization : area is = "+area); } } Output :
C:\java> javac VariableTest.java C:\java> java VariableTest
Normal initialization: area is = 200 Dynamic initialization: area is = 200
The Scope and Lifetime of Variables Every variable have scope and life time throughout the program. Here we study when the new scope will be create for how long time (Life time). A block is begun with an opening curly brace and ended by a closing curly brace. A block defines a scope. We use so many variables in our program and declared these variables at the at the start of the main( ) method. Most other computer languages define two general categories of scopes: global and local. However, these traditional scopes do not fit well with Java‘s strict, object oriented model.
Prog.No.:- 6 // Demonstrate variable scope. class Scope { public static void main(String args[]) { int x;
// known to all code within main
x = 10;
INTERNET TECHNOLOGY (CORE JAVA)
if(x == 10) {
// start new scope int y = 20;
// known only to this block // x and y both known here.
System.out.println("x and y: " + x + " " + y); } y = x+10;
// Error! y not known here // x is still known here.
System.out.println("x is " + x); } }
Here we initialize variable x in main block but the variable y is initialized in if block so scope of variable y is limited to if block. So we will get error on line no. 14 because we are trying to access variable y which is outside of its scope.
Array: It is a group of variables with same data types.
Java has three reference data types: Data Type
Description A collection of several items of the same data type. For example names of Array student. A collection of variables and methods. Class An abstract class created to implement multiple inheritance in JAVA. Interface
We have one dimensional and multidimensional array in java. It works differently compare to C and C++ language. We declare one char type array and size of that array is 10. So we have 10 different char type variables like ch[0] to ch[9]. Value in the square bracket is called index of the array and index value of any array always start from 0.
Arrays can be declared in three ways: Description
Only Declaration Declaration and creation
Syntax
Example char ch[ ]; declares a Just declares the data type identifier[] character array named array. ch. Declares and allocates char ch[] = new memory for the array data type identifier[] char[10]; declares an elements using the =new data type[size]; array ch to store 10 reserved word ‗new‘. characters.
INTERNET TECHNOLOGY (CORE JAVA)
char ch[] Declares the array, data type identifier[] ={‗A‘,‘B‘,‘C‘,‘D‘}; Declaration, creation allocates memory for = {value1, value2, declares an array ch to it and assigns initial and initialization ….ValueN}; store 4 pre-as signed values to its elements. character values.
Syntax of One dimensional array : Declaration syntax : type var-name[ ]; Exp. int month[ ]; Here we just declare month variable of type int array. But actually or physically no array exists. To link this array into actual physical array of integers we have to use new keyword. Syntax: array-var = new type[size]; Exp. month = new month[12]; So obtaining an array is a two-step process. First, you must declare a variable of the desired array type. Second, you must allocate the memory that will hold the array, using new, and assign it to the array variable. Thus, in Java all arrays are dynamically allocated. Now we have 12 different int type variable month[0] to month[11]. It is possible to combine the declaration of the array variable with the allocation of the array itself like... int month[] = new int[12]; Array declare either primitive or class. char [] s; Point [] p; Declaring array with the bracket to left, the bracket apply to all variables to the right of the brackets. int a[], b;// a is array and b is int type variable. int [] a, b; // a and b both are int type array. In java array is an object even when the array is made up of primitive type and as with other class type, the declaration does not create the object itself. Instead, the declaration of an array creates a reference that we can use to refer to an array. Actual memory used by the array elements is allocated dynamically either by new statement or by an array initializer.
EX:public char [] createArray() { char [] s; s= new char[26]; // create 26 char value array. for(int i=0; i<26;i++) { S[i]=(char)(‗A‘+i); } return s; }
INTERNET TECHNOLOGY (CORE JAVA)
Execution Stack createArray Char[] s this main
A B C D Z Heap Memory
Fig. 1 NOTE:- Indexes the individual array elements always begins from 0 and must be maintained in the legal Range: greater than 0 or equal to 0 and less than the array length. Any attempt to access an array element outside these bounds causes a runtime exception.
Creating Reference Array:P=new Point[10]; // create an array of the 10 references of type Point. However, it does not create 10 Point objects. public char [] createArray() { Point [] p ; p= new Point[10]; for(int i=0; i<10;i++) { p[i]=new Point(i, i+1); } return p; }
Execution Stack
Point []
createArray
p this main Heap Memory
Fig. 2
INTERNET TECHNOLOGY (CORE JAVA)
Initializing Arrays:When we create an array every element is initialized. In case of char, each value is initialized to the null(‗\u0000‘) character. In case of array p each value is initialized to null, indicating that it does not refer to a Point object. After the assignment P[0]=new Point(), the first element of the array refer to real Point object. NOTE:Initializing all variables i including elements of arrays is essential to the security of the system. We must not use variables in an uninitialized state. Multidimensional array : Declaration syntax : type var-name[ ][ ]; Exp. int mat[ ][ ] = new int[4][5]; In Java, multidimensional arrays are actually arrays of arrays. To declare a multidimensional array variable, specify each additional index using another set of square brackets. This allocates a 4 by 5 array and assigns it to mat. Internally this matrix is implemented as an array of arrays of int. conceptually.
Fig. 3[Indexing of multi dimensional array]
OPERATOR IN JAVA Operator: It is a symbol that tells the computer to perform mathematical and logical calculation. Java supports basically 6 types of operators. 1. Arithmetic operator 2. Bitwise operator 3. Relational operator 4. Boolean Logical operator 5. Assignment operator 6. Conditional operator
Arithmetic operator Prog. No.:- 7 public class ArithmeticTest { public static void main(String[] args)
INTERNET TECHNOLOGY (CORE JAVA)
{ System.out.println("..............Arithmetic operators................."); System.out.println(); int a = 10; int b = 3; int c = 20; int d = 30; int e = 40; int f = 50; int i = 10; int j = 5; int m = 30; int l = 3; int o = 25; int v = 6; int z = 27; int r = 8; int add = a + b; int sub = a - b; int mul = a * b; int div = a / b; int mod = a % b; System.out.println("<-------Basic Arithmetic operators------->"); System.out.println("Addition of a and b : a + b = 10 + 3 = "+add); System.out.println("Subtraction of a and b : a - b = 10 - 3 = "+sub); System.out.println("Multiplication of a and b : a * b = 10 * 3 = "+mul); System.out.println("Division of a and b : a / b = 10 / 3 = "+div); System.out.println("Modulus of a and b : a % b = 10 % 3 = "+mod); System.out.println(); System.out.println("<-------Increment Operator------->"); // c = 20, d = 30 // post_incr = c++ => post_incr = c then c = c + 1 => post_incr = 20 and c = 20 + 1 = 21 // pre_incr = ++d => d = d + 1 then pre_incr = d => d = 30 + 1 = 31 and pre_incr = 31
System.out.println("Before Post-Increment of c = "+c); int post_incr = c++; System.out.println("Post-Increment of c : c++ = 20++ = "+post_incr); System.out.println("After Post-Increment of c = "+c); System.out.println("Before Pre-Increment of d = "+d); int pree_incr = ++d; System.out.println("Pree-Increment of d : ++d = ++30 = "+pre_incr); System.out.println("After Pre-Increment of d = "+d); System.out.println(); System.out.println("<-------Decrement Operator------->"); /* e = 40, f = 50 * post_decr = e-- => post_decr = e then e = e - 1 => post_decr = 40 and c = 40 - 1 = 39 * pre_decr = --f => f = f - 1 then pre_decr = f => f = 50 - 1 = 49 and pre_decr = 49 */ System.out.println("Before Post-Decrement of c = "+e);
INTERNET TECHNOLOGY (CORE JAVA)
int post_decr = e--; System.out.println("Post-Decrement of e : e-- = 40-- = "+post_decr); System.out.println("After Post-Decrement of e = "+e); System.out.println("Before Pre-Decrement of f = "+f); int pree_decr = --f; System.out.println("Pree-Decrement of f : --f = --50 = "+pre_decr); System.out.println("After Pre-Decrement of f = "+f); System.out.println(); System.out.println("<-------Assignment Operators------->"); System.out.println("Addition Assignment of a and b : a += b means 10+=3 => a = a + b => a = 10 + 3 = "+(a+=b)); System.out.println("Subtraction Assignment of i and j : i -= j means 10-=5 => i = i - j => i = 10 - 5 = "+(i-=j)); System.out.println("Multiplication Assignment of m and l : m *=l means 30*=3 => m = m * l => m = 30 * 3 = "+(m*=l)); System.out.println("Division Assignment of o and v : o /= v means 25/=6 => o = o / v => o = 25 / 6 = "+(o/=v)); System.out.println("Modulus Assignment of z and r : z %= r means 27%=8 => z = z % r => z = 27 % 8 = "+(z%=r)); } }
Output : C:\java> javac ArithmeticTest.java C:\java> java ArithmeticTest ..............Arithmetic operators................. <-------Basic Arithmetic operators-------> Addition of a and b : a + b = 10 + 3 = 13 Subtraction of a and b : a - b = 10 - 3 = 7 Multiplication of a and b : a * b = 10 * 3 = 30 Division of a and b : a / b = 10 / 3 = 3 Modulus of a and b : a % b = 10 % 3 = 1 <-------Increment Operator-------> Before Post-Increment of c = 20 Post-Increment of c : c++ = 20++ = 20 After Post-Increment of c = 21 Before Pree-Increment of d = 30 Pree-Increment of d : ++d = ++30 = 31 After Pree-Increment of d = 31 <-------Decrement Operator-------> Before Post-Decrement of c = 40 Post-Decrement of e : e-- = 40-- = 40 After Post-Decrement of e = 39 Before Pree-Decrement of f = 50 Pree-Decrement of f : --f = --50 = 49 After Pree-Decrement of f = 49 <-------Assignment Operators-------> Addition Assignment of a and b : a += b means 10+=3 => a = a + b => a = 10 + 3 = 13 Subtraction Assignment of i and j : i -= j means 10-=5 => i = i - j => i = 10 - 5 = 5 Multiplication Assignment of m and l : m *=l means 30*=3 => m = m * l => m = 30 * 3 = 90 Division Assignment of o and v : o /= v means 25/=6 => o = o / v => o = 25 / 6 = 4 Modulus Assignment of z and r : z %= r means 27%=8 => z = z % r => z = 27 % 8 = 3
Bitwise operator Prog. No.:- 8 public class BitewiseTest
INTERNET TECHNOLOGY (CORE JAVA)
{ public static void main(String[] args) { System.out.println("..............Bitewise operators................."); System.out.println("<-------Bitewise Logical Operators------->"); String binary[] = {"0000", "0001", "0010", "0011", "0100", "0101", "0110", "0111", "1000", "1001", "1010", "1011", "1100", "1101", "1110", "1111"}; int a = 2; // 0 + 0 + 2 + 0 or 0010 in binary int b = 7; // 0 + 4 + 2 + 1 or 0111 in binary int c = a | b; //Bitwise AND operator int d = a & b; //Bitwise OR operator int e = a ^ b; //Bitwise XOR(exclusive OR) operator int f = ~a & a ; //Bitwise unary NOT operator, a = 0010 so ~a = 1101 hence f = ~a & a = 1101 & 0010 = 0000 int g = (~a & b) | (a & ~b); System.out.println("The binary value of a = " + binary[a]); System.out.println("The binary value of b = " + binary[b]); System.out.println("The Bitwise OR : a | b = " + binary[c] + " and Decimal value = "+c); System.out.println("The Bitwise AND : a & b = " + binary[d] + " and Decimal value = "+d); System.out.println("The Bitwise XOR(exclusive OR) : a ^ b = " + binary[e] + " and Decimal value = "+e); System.out.println("The Bitwise unary NOT : ~a & a = " + binary[f] + " and Decimal value = "+f); System.out.println("~a&b|a&~b = " + binary[g]+ " and Decimal value = "+g); System.out.println(); System.out.println("<-------Bitewise Shift Operators------->"); System.out.println("The original binary value of a = " +binary[a] + " and Decimal value of a = "+a); a = a << 2; //Bitwise Left shift operator System.out.println("The Left shift : a = a << 2 means a = 0010 << 2 hence a = "+binary[a] + " and Decimal value of a = "+a); System.out.println("The original binary value of b = " +binary[b] + " and Decimal value of b = "+b); b = b >> 2; //Bitwise Right shift operator System.out.println("The Right shift : b = b >> 2 means b = 0111 >> 2 hence b = "+binary[b] + " and Decimal value of b = "+b); int u = -1; System.out.println("The original decimal value of u = " +u); u = u >>> 30; //Bitwise Unsigned Right shift operator System.out.println("The Unsigned Right shift : u = u >>> 30 means u = 11111111 11111111 11111111 11111111 >>> 30 hence u = "+binary[u] + " and Decimal value of u = "+u); System.out.println(); System.out.println("<-------Bitewise Assignment Operators------->"); int p = 5; System.out.println("The original binary value of p = " +binary[p] + " and Decimal value of p = "+p); p >>= 2; //Bitewise shift Right Assignment Operator System.out.println("The Bitewise Shift Right Assignment Operators : p >>= 2 means p = p >> 2 hence p = 0101 >> 2 so p = "+binary[p] + " and Decimal value of p = "+p);
INTERNET TECHNOLOGY (CORE JAVA)
/*Same as you can check Bitwise AND assignment,Bitwise OR assignment,Bitwise exclusive OR assignment, Shift right zero fill assignment,Shift left assignment */ } }
Output : C:\java> javac BitewiseTest.java C:\java> java BitewiseTest ..............Bitewise operators................. <-------Bitewise Logical Operators-------> The binary value of a = 0010 The binary value of b = 0111 The Bitwise OR : a | b = 0111 and Decimal value = 7 The Bitwise AND : a & b = 0010 and Decimal value = 2 The Bitwise XOR(exclusive OR) : a ^ b = 0101 and Decimal value = 5 The Bitwise unary NOT : ~a & a = 0000 and Decimal value = 0 ~a&b|a&~b = 0101 and Decimal value = 5 <-------Bitewise Shift Operators-------> The original binary value of a = 0010 and Decimal value of a = 2 The Left shift : a = a << 2 means a = 0010 << 2 hence a = 1000 and Decimal value of a = 8 The original binary value of b = 0111 and Decimal value of b = 7 The Right shift : b = b >> 2 means b = 0111 >> 2 hence b = 0001 and Decimal value of b = 1 The original decimal value of u = -1 The Unsigned Right shift : u = u >>> 30 means u = 11111111 11111111 11111111 11111111 >>> 30 hence u = 0011 and Decimal value of u = 3 <-------Bitewise Assignment Operators-------> The original binary value of p = 0101 and Decimal value of p = 5 The Bitewise Shift Right Assignment Operators : p >>= 2 means p = p >> 2 hence p = 0101 >> 2 so p = 0001 and Decimal value of p = 1
Relational operator Prog. No.:- 9 public class RelationalTest { public static void main(String[] args) { System.out.println("..............Relational operators................."); int mark = 70; if(mark != 0) // != Not equal to { if(mark == 65 | mark > 65) // == Equal to, > Greater than System.out.println("Congratulation ,You got a distinction and you got " + mark + " marks........"); else if (mark < 65 & 60 <= mark) // < Less than, <= Less than or equal to System.out.println("Congratulation ,You got a First class and you got " + mark + " marks........"); else if (mark < 60 & mark >= 50) System.out.println("You got a Second class and you got " + mark + " marks........"); else if (50 > mark & mark >= 40) // > Greater than, >= Greater than or equal to System.out.println("You got a Third class and you got " + mark + " marks........");
INTERNET TECHNOLOGY (CORE JAVA)
else System.out.println("You are failed and you got " + mark + " marks........"); } else System.out.println("Please give the valid mark..............."); } }
Output : C:\java> javac RelationalTest.java C:\java> java RelationalTest ..............Relational operators................. Congratulation ,You got a distinction and you got 70 marks........
Boolean Logical operator Prog. No.:- 10 public class Boolean_LogicalTest { public static void main(String[] args) { System.out.println("..............Boolean Logical Operators................."); System.out.println("<---------Basic Boolean Logical Operators--------->"); boolean a = false; boolean b = true; boolean c = a | b; //Logical AND operator boolean d = a & b; //Logical OR operator boolean e = a ^ b; //Logical XOR(exclusive OR) operator boolean f = (!a & b) | (a & !b); boolean g = !a; //Logical unary NOT operator System.out.println(" a = " + a); System.out.println(" b = " + b); System.out.println("Boolean Logical OR : a | b = " + c); System.out.println("Boolean Logical AND : a & b = " + d); System.out.println("Boolean Logical XOR(exclusive OR) : a ^ b = " + e); System.out.println("(!a & b) | (a & !b) = " + f); System.out.println("!a = " + g); System.out.println(); System.out.println("<---------Boolean Logical Assignment Operators-------->"); System.out.println("Before apply assignment operator, the value of a = "+a); a &= b; // System.out.println("After apply assignment operator : a &= b means a = a & b hence now the value of a : "+a); /*Same as you can check Boolean OR assignment,Boolean exclusive OR assignment, Boolean Equal to and Boolean Not equal to */ } }
Output : C:\java> javac Boolean_LogicalTest.java C:\java> java Boolean_LogicalTest ..............Boolean Logical Operators................. <---------Basic Boolean Logical Operators--------->
INTERNET TECHNOLOGY (CORE JAVA)
a = false b = true Boolean Logical Boolean Logical Boolean Logical (!a & b) | (a & !a = true
OR : a | b = true AND : a & b = false XOR(exclusive OR) : a ^ b = true !b) = true
<---------Boolean Logical Assignment Operators---------> Before apply assignment operator, the value of a = false After apply assignment operator : a &= b means a = a & b hence now the value of a : false
Prog. No.:- 11 public class Boolean_ShortCircuitTest { public static void main(String[] args) { System.out.println("<---------Boolean Short-Circuit Operators--------->"); int i = 10; int j = 20; if (i != 10 && ++j/i>0) { System.out.println("i = "+i); System.out.println("j = "+j); } System.out.println("In Short-circuit AND operator(&&): "); System.out.println("Not checked the second condition in IF-BLECK if first condition is false........."); System.out.println("So,the value of j = "+j); //Same as you can check Short-circuit OR operator(||) } }
Output : C:\java> javac Boolean_ShortCircuitTest.java C:\java> java Boolean_ShortCircuitTest <---------Boolean Short-Circuit Operators---------> In Short-circuit AND operator(&&): Not checked the second condition in IF-BLECK if first condition is false......... So,the value of j = 20
Assignment operator var = expression; int x, y, z; x = y = z = 50; // set x, y, and z to 50
Prog. No.:- 12 public class Assignment_OperatorTest { public static void main(String[] args) { System.out.println("<------------Assignment Operator------------->"); int x,y,z,sum; x = y = z = 50; //The Assignment Operator which assign the value to a varible sum = x + y + z; System.out.println("x + y + z = "+sum);
INTERNET TECHNOLOGY (CORE JAVA)
} }
Output : C:\java> javac Assignment_OperatorTest.java C:\java> java Assignment_OperatorTest <------------Assignment Operator-------------> x + y + z = 150
Conditional operator It is also known as ternary operator or conditional operator. Syntax:- expression1 ? expression2 : expression3 b = a < 0 ? -a : a;
Prog. No.:- 13 public class TernaryTest { public static void main(String[] args) { int a, b; a = 50; b = a < 0 ? -a : a; // get absolute value System.out.println("The Absolute value of a = -10; b = a < 0 ? -a : a; // get absolute value System.out.println("The Absolute value of } }
of a "+ a + " is " + b); of a "+ a + " is " + b);
Output : C:\java> javac TernaryTest.java C:\java> java TernaryTest The Absolute value of 50 is 50 The Absolute value of -10 is 10
SCANNER Import java.uti.Scanner because the Scanner class is inside util package of java library. Than we create reference (object) of class Scanner named s. "System.in" This is the predefine library which allow user to enter value in any variable at run time through keyboard. We can say same as scanf() in c and cin >> in c++.
Now in Scanner class there are so many different different methods for scaning different type of values. In-built methods of Scanner class for scanning different types of values. 1. nextByte() for scanning byte type value. 2. nextShort() for scanning short type value. 3. nextInt() for scanning int type value. 4. nextLong() for scanning long type value. 5. nextFloat() for scanning floting point value. 6. nextDouble() for scanning double type value. 7. next() for scanning a string.
Prog. No.:- 14 import java.util.Scanner; public class ScannerTest {
INTERNET TECHNOLOGY (CORE JAVA)
public static void main(String[] args) { Scanner s = new Scanner(System.in); // Here we initialize object s for Scanner class. System.out.print("Enter the first value a : "); int a = s.nextInt(); // Scan int type value System.out.print("Enter the second value b : "); int b = s.nextInt(); // Scan int type value int sum = a + b; System.out.println("The addition of a and b : a + b = "+sum); } }Output : C:\java> javac ScannerTest.java C:\java> java ScannerTest Enter the first value a : 5 Enter the second value b : 6 The addition of a and b : a + b = 11
CONTROL STATEMENTS IN JAVA Selection Statements If selection statements Switch selection statement Looping statements Jump Statements
Selection Statements Java supports two selection statements: if and switch. These statements allow you to control the flow of your program‘s execution based upon conditions known only during run time. if in java: The if statement is Java’s conditional branch statement. It can be used to route program execution through two different paths. Syntax : if (condition) { statement1; } When the condition is true the Statement within the if is executed. After that execution continues with the next statement after the if statement. If the condition is false then the statement within the if is not executed and the execution continues with the statement after the if statement.
Prog. No.:- 15 import java.util.Scanner; class larger { public static void main(String args[]) { int x1,x2,x3;
INTERNET TECHNOLOGY (CORE JAVA)
int large; Scanner s = new Scanner(System.in); System.out.println("Enter value for x1 : x1=s.nextInt(); System.out.println("Enter value for x2 : x2=s.nextInt(); System.out.println("Enter value for x3 : x3=s.nextInt(); large = x1; if (x2 > large) large = x2; if (x3 > large) large = x3; System.out.println("\n\n\tLargest number
"); "); ");
= " + large);
} }
Output : C:\java> javac larger.java C:\java> java larger Largest number = 20
NOTE: The number of statement in if block is only one than parentheses are optional but if it‘s more than one than parentheses are compulsory. And if we enter the same value in x1, x2 and x3 in above program than largest number is x1 because our both condition will be false because here we checked only > not >=. EX. if (condition) { Statement 1; Statement 2; } Same as above, except that here multiple statements are executed if the condition Is true.
if else : Syntax : if (condition) { statement1; } else { statement2; } if else work like this: If the condition is true, then statement1 is executed. Otherwise, statement2 is executed. In no case will both statements be executed.
Prog. No.:- 16 import java.util.Scanner;
INTERNET TECHNOLOGY (CORE JAVA)
class result { public static void main(String args[]) { Scanner s = new Scanner(System.in); System.out.println("Enter marks : "); int marks = s.nextInt(); if (marks<40) System.out.println("\nThe student has failed .. "); else System.out.println("\nThe student has Passed .. "); } }
Output : C:\java> javac result.java C:\java> java result The student has passed...
if-else-if Ladder : Syntax : if(condition) statements; else if(condition) statemenst; else if(condition) statements; ... ... else statements; The if statements are executed from the top down. As soon as one of the conditions controlling the if is true, the statement associated with that if is executed, and the rest of the ladder is bypassed. If none of the conditions is true, then the final else statement will be executed. The final else acts as a default condition; that is, if all other conditional tests fail, then the last else statement is performed. If there is no final else and all other conditions are false, then no action will take place.
Prog. No.:- 17 import java.util.Scanner; class Day { public static void main(String args[]) { Scanner s = new Scanner(System.in); System.out.println("Enet day between 0 to 6 Day = "); int day = s.nextInt(); if (day == 0) { System.out.println("\n Sunday"); } else if (day == 1) { System.out.println("\n Monday"); } else if (day == 2)
INTERNET TECHNOLOGY (CORE JAVA)
{ System.out.println("\n } else if (day == 3) { System.out.println("\n } else if (day == 4) { System.out.println("\n } else if (day == 5) { System.out.println("\n } else { System.out.println("\n }
Tuesday");
Wednesday");
Thursday");
Friday");
Saturday");
} }
Output : C:\java> javac Day.java C:\java> java Day Tuesday
Nested if : A nested if is an if statement that is the target of another if or else. Syntax : if(condition) { if(condition) statements.... else statements.... } else { if(condition) statements.... else statements.... }
Prog. No.:- 18 import java.util.Scanner; class MaxValue { public static void main(String args[]) { int a,b,c;
INTERNET TECHNOLOGY (CORE JAVA)
int max=0; Scanner s = new Scanner(System.in); System.out.println("Enter value for a : "); a=s.nextInt(); System.out.println("Enter value for b : "); b=s.nextInt(); System.out.println("Enter value for c : "); c=s.nextInt(); if (a>b) { if(a>c) max=a; else //This else is associate with this if(a>c) max=c; } else //This else is associate with this if(a>b) { if(b>c) max=b; else //This else is associate with this if(b>c) max=c; } System.out.println("\n max value = " +max); } }
Output : C:\java> javac MaxValue.java C:\java> java MaxValue max value = 15
switch : The switch statement is Java’s multi branch statement. It provides an easy way to dispatch execution to different parts of your code based on the value of an expression. It is difficult to understand large number of if else..if statements. So we have switch statement. Syntax : switch (expression) { case value 1 : statement 1 ; break; case value 2 : statement 2 ; break; ... ... case value N : statement N ; break; default : statements ; break; } The expression must be of type byte, short, int, or char; each of the values specified in the case statements must be of a type compatible with the expression. Each case value must be a unique literal (constant, not a variable). Duplicate case values are not allowed. The value of the expression is compared with each ‘case’ values. If a match is found, the corresponding statement or statements are executed. If no match is found, statement or statements in the default case are executed. Default statement is optional. If default statement is absent, then if no matches
INTERNET TECHNOLOGY (CORE JAVA)
are found, then the switch statement completes without doing anything. The break statement is used inside the switch to terminate a statement sequence.
Prog. No.:- 19 import java.util.Scanner; public class Calculator { public static void main(String[] args) { int a,b,ch; double ans; Scanner s = new Scanner(System.in); System.out.print("Enter a : "); a=s.nextInt(); System.out.print("Enter b : "); b=s.nextInt(); System.out.println("Enter 1 for addition"); System.out.println("Enter 2 for subtraction"); System.out.println("Enter 3 for multiplication"); System.out.println("Enter 4 for division"); System.out.print("Enter your choice : "); ch=s.nextInt(); switch(ch) { case 1: ans=a+b; System.out.println("a + b = " + ans); break; case 2: ans=a-b; System.out.println("a - b = " + ans); break; case 3: ans=a*b; System.out.println("a * b = " + ans); break; case 4: ans=a/b; System.out.println("a / b = " + ans); break; default: System.out.println("Enter correct choice"); } } }
Output : C:\java> javac Calculator.java C:\java> java Calculator Enter a : 5 Enter b : 6 Enter 1 for addition Enter 2 for subtraction Enter 3 for multiplication Enter 4 for division Enter your choice : 3 a * b = 30.0
INTERNET TECHNOLOGY (CORE JAVA)
Looping statements Java‘s repetition (iteration) statements are for, while, and do-while. These statements create what we commonly call loops. A loop repeatedly executes the same set of instructions until a termination condition is met.
1. for :
The for loop repeats a set of statements a certain number of times until a condition is matched. It is commonly used for simple iteration. The for loop appears as shown below.
Syntax : for (initialization; condition; expression) { Set of statements; } In the first part a variable is initialized to a value. The second part consists of a test condition that returns only a Boolean value. The last part is an expression, evaluated every time the loop is executed.
Prog. No.:- 20
class ForTest { public static void main(String args[]) { int i; for (i=0;i<10;i++) { System.out.println("\nHELLO ! This is java For Loop."); } } }
Output : C:\java> javac ForTest.java C:\java> java ForTest HELLO ! This is java For Loop. HELLO ! This is java For Loop. HELLO ! This is java For Loop. HELLO ! This is java For Loop. HELLO ! This is java For Loop. HELLO ! This is java For Loop. HELLO ! This is java For Loop. HELLO ! This is java For Loop. HELLO ! This is java For Loop. HELLO ! This is java For Loop.
INTERNET TECHNOLOGY (CORE JAVA)
2. while :
The while loop executes a set of code repeatedly until the condition returns false.
Syntax : while (condition) { body(statements) of the loop } Where is the condition to be tested. If the condition returns true then the statements inside the are executed. Else, the loop is not executed.
Prog. No.:- 21 class WhileTest { public static void main(String args[]) { int i=1; while(i<=10) { System.out.println("\n" + i); i++; } } }
Output : C:\java> javac WhileTest.java C:\java> java WhileTest 1 2 3 4 5 6 7 8 9 10
3. do while :
The do while loop is similar to the while loop except that the condition to be evaluated is given at the end. Hence the loop is executed at least once even when the condition is false.
Syntax : do { body of the loop } while (condition); In do while loop semicolon(;) is compulsory after while.
INTERNET TECHNOLOGY (CORE JAVA)
NOTE : for and while loops are entry control loop because here conditions are checked at entry time of loop but do while loop is exit control loop because the condition is checked at exit time.
Prog. No.:- 22 class {
DowhileTest public static void main(String args[]) { int i = 1; int sum = 0; do { sum = sum + i; i++; }while (i<=10); System.out.println("\n\n\tThe sum of 1 to 10 is .. " + sum); }
}
Output : C:\java> javac DowhileTest.java C:\java> java DowhileTest The sum of 1 to 10 is .. 55
Nested loops : Java allows loops to be nested. That is, one loop may be inside another. It can help you to scan and print multi dimensional array as well as in so many other application or program.
Prog. No.:- 23 Class NestedTest { public static void main(String args[]) { int i, j; for(i=0; i<10; i++) { for(j=i; j<10; j++) { System.out.print("."); } System.out.println(); } } }
Output : C:\java> javac NestedTest.java C:\java> java NestedTest .......... ......... ........ ....... ...... ..... .... ... ..
INTERNET TECHNOLOGY (CORE JAVA)
.
Jump Statements Java supports three jump statements: break, continue, and return. These statements transfer control to another part of your program. 1. break. 2. continue. 3. return.
The break statement
This statement is used to jump out of a loop. Break statement was previously used in switch – case statements. On encountering a break statement within a loop, the execution continues with the next statement outside the loop. The remaining statements which are after the break and within the loop are skipped. Break statement can also be used with the label of a statement.
statementName : SomeJavaStatement
When we use break statement along with label as
break statementName; The execution continues with the statement having the label. This is equivalent to a goto statement of c and c++
Prog. No.:- 24 class BreakTest { public static void main(String args[]) { int i = 1; while (i<=10) { System.out.println("\n" + i); i++; if (i==5) { break; } } } }
Output : C:\java> javac BreakTest.java C:\java> java BreakTest 1 2 3 4 5
Break to a label Prog. No.:- 25 class BreakT {
INTERNET TECHNOLOGY (CORE JAVA)
public static void main (String args[]) { boolean t=true; a: { b: { c: { System.out.println("Before the break"); if(t) break b; System.out.println("This will not execute"); } System.out.println("This will not execute"); } System.out.println("This is after b"); } } }
Output : C:\java> javac BreakT.java C:\java> java BreakT Before the break This is after b
Continue statement
This statement is used only within looping statements. When the continue statement is encountered, the next iteration starts. The remaining statements in the loop are skipped. The execution starts from the top of loop again.
Prog. No.:- 26 class ContinueTest { public static void main(String args[]) { for (int i=1; i<1=0; i++) { if (i%2 == 0) continue; System.out.println("\n" + i); } } }
Output : C:\java> javac ContinueTest.java C:\java> java ContinueTest 1 3 5 7 9
INTERNET TECHNOLOGY (CORE JAVA)
The return statement
The last control statement is return. The return statement is used to explicitly return from a method. That is, it causes program control to transfer back to the caller of the method. The return statement immediately terminates the method in which it is executed.
Prog. No.:- 27 class ReturnTest { public static void main(String args[]) { boolean t = true; System.out.println("Before the return."); if(t) return; // return to caller System.out.println("This won't execute."); } }
Output : C:\java> javac ReturnTest.java C:\java> java ReturnTest Before the return.
NOTE : the if(t) statement is necessary. Without it, the Java compiler would flag an ―unreachable code‖ error, because the compiler would know that the last println( ) statement would never be executed. To prevent this error, the if statement is used here to trick the compiler for the sake of this demonstration.
INTRODUCTION TO CLASS IN JAVA Class Class is a collection of data members and member functions. Data members Data members are nothing but simply variables that we declare inside the class so it called data member of that particular class. Member functions Member functions are the function or you can say methods which we declare inside the class so it called member function of that particular class. The most important thing to understand about a class is that it defines a new data type. Once defined, this new type can be used to create objects of that type. Thus, a class is a template for an object, and an object is an instance of a class. Because an object is an instance of a class, you will often see the two words object and instance used interchangeably. Syntax of class: class classname { type instance-variable1; type instance-variable2; //.... type instance-variableN; type methodname1(parameter-list) { // body of method }
INTERNET TECHNOLOGY (CORE JAVA)
type methodname2(parameter-list) { // body of method } // ... type methodnameN(parameter-list) { // body of method } }
When we define a class, you declare its exact form and nature. We do this by specifying the data that it contains and the code that operates on that data. The data, or variables, defined within a class are called instance variables. The code is contained within methods. NOTE : C++ programmers will notice that the class declaration and the implementation of the methods are stored in the same place and not defined separately.
Prog. No.:- 28 public class Coordinate { int x = 0; int y = 0; void displayPoint() { System.out.println("Printing the coordinates"); System.out.println(x + " " + y); } public static void main(String args[]) { MyPoint obj; // declaration obj = new MyPoint(); // allocation of memory to an object obj.x=10; //access data member using object. obj.y=20; obj.displayPoint(); // calling a member method } }
Output : C:\java> javac Coordinate.java C:\java> java Coordinate Printing the coordinates 10 20
Here x and y are data members of class MyPoint and displayPoint() is a member function of the same class. Syntax: accessing data member of the class: objectname.datamember name; accessing methods of the class: objectname.method name(); So for accessing data of the class: we have to use (.) dot operator. NOTE: we can use or access data of any particular class without using (.) dot operator from inside that particular class only.
How to declare object of class in java? Syntax of object: classname objectname; \\ declaration of object. objectname = new classname(); \\ allocate memory to object (define object).
INTERNET TECHNOLOGY (CORE JAVA)
or we can directly define object like this classname objectname = new classname();
Prog. No.:- 29 class Box { double width; double height; double depth; } class BoxTest { public static void main(String args[]) { Box mybox1 = new Box(); Box mybox2 = new Box(); double vol; // assign values to mybox1's instance variables mybox1.width = 10; mybox1.height = 20; mybox1.depth = 15; /* assign different values to mybox2's instance variables */ mybox2.width = 3; mybox2.height = 6; mybox2.depth = 9; // compute volume of first box vol = mybox1.width * mybox1.height * mybox1.depth; System.out.println("Volume is " + vol); // compute volume of second box vol = mybox2.width * mybox2.height * mybox2.depth; System.out.println("Volume is " + vol); } }
Output : C:\java> javac BoxTest.java C:\java> java BoxTest Volume is 3000.0 Volume is 162.0
In program we can understand that each object has its own copies of the instance variables. This means that if you have two Box objects, each has its own copy of depth, width, and height. It is important to understand that changes to the instance variables of one object have no effect on the instance variables of another. Assigning Object Reference Variables : Suppose Box b1 = new Box(); Box b2 = b1; Here b1 is the object of class Box. And we assign b1 to b2 by b2=b1. Here we did not use new keyword for b2 so b1 and b2 will both refer to the same object. The assignment of b1 to b2 did not allocate any memory or copy any part of the original object. It simply makes b2 refer to the same object as does b1.Thus, any changes made to the object through b2 will affect the object to which b1 is referring, since they are the same object.
INTERNET TECHNOLOGY (CORE JAVA)
NOTE: When you assign one object reference variable to another object reference variable, you are not creating a copy of the object, you are only making a copy of the reference.
INTRODUCTION OF METHOD Classes usually consist of two things instance variables and methods. Methods are defined as follows:
Return type Name of the method A list of parameters Body of the method.
Syntax: return type method name (list of parameters) { //Body of the method } return type specifies the type of data returned by the method. This can be any valid data type including class types that you create. If the method does not return a value, its return type must be void, Means you can say that void means no return. Methods that have a return type other than void return a value to the calling routine using the following form of the return statement: return value; The list of parameter is a sequence of type and identifier pairs separated by commas. Parameters are essentially variables that receive the value of the arguments passed to the method when it is called. If the method has no parameters, then the parameter list will be empty. Class which have methods and data members both
Prog. No.:- 30 import java.util.Scanner; class Box1 { double width; double height; double depth; void volume() // display volume of a box { System.out.print("Volume is : "); System.out.println(width * height * depth); } } class Box1Test { public static void main(String args[]) { Box box1 = new Box(); // defining object box1 of class Box Scanner s = new Scanner(System.in);
INTERNET TECHNOLOGY (CORE JAVA)
System.out.print(“Enter Box Width : ”); box1.width = s.nextDouble(); System.out.print(“Enter Box Height : ”); box1.height = s.nextDouble(); System.out.print(“Enter Box Depth : ”); box1.depth = s.nextDouble(); // display volume of box1 box1.volume(); // calling the method volume } }
Output: C:\java> javac Box1Test.java C:\java> java Box1Test Enter Box Width : 15 Enter Box Height : 20 Enter Box Depth : 10 Volume is : 3000.00
Width, height and depth are data members of class Box and void volume () is method of class Box. Method has no parameter and no return value. Program in different way
Prog. No.:- 31 import java.util.Scanner; class Box2 { double width; double height; double depth; double volume() { return width * height * depth; } } class Box2Test { public static void main(String args[]) { double vol; Box box1 = new Box(); // defining object box1 of class Box Scanner s = new Scanner(System.in); System.out.print(“Enter Box Width : ”); box1.width = s.nextDouble(); System.out.print(“Enter Box Height : ”); box1.height = s.nextDouble(); System.out.print(“Enter Box Depth : ”); box1.depth = s.nextDouble(); // display volume of box1 vol = box1.volume(); // calling the method volume System.out.println("Volume is : " +vol); } }
Output:
INTERNET TECHNOLOGY (CORE JAVA)
C:\java> javac Box2Test.java C:\java> java Box2Test Enter Box Width : 15 Enter Box Height : 20 Enter Box Depth : 10 Volume is : 3000.00
In program volume() method has return type double so we took one vol variable. It is a local variable of class BoxDemo and it catches the returned value by volume method of class Box. One thing must keep in mind that the data type of vol and return type of volume() method always be same
Prog. No.:- 32 import java.util.Scanner; class Box3 { double width; double height; double depth; double volume(double w, double h, double d) { return width * height * depth; } } class Box3Test { public static void main(String args[]) { double vo,wth,ht,dth; Box box1 = new Box(); // defining object box1 of class Box Scanner s = new Scanner(System.in); System.out.print(“Enter Box Width : ”); wth = s.nextDouble(); System.out.print(“Enter Box Height : ”); ht = s.nextDouble(); System.out.print(“Enter Box Depth : ”); dth = s.nextDouble(); // display volume of box1 vol = box1.volume(wth,ht,dth); // calling the method volume System.out.println("Volume is : " +vol); } }
Output: C:\java> javac Box3Test.java C:\java> java Box3Test Enter Box Width : 15 Enter Box Height : 20 Enter Box Depth : 10 Volume is : 3000.00
In program volume() method has three parameters as well as double return type. One thing must keep in mind that in defining and calling of method, the sequence of data type of parameter must be same in both.
CONSTRUCTOR IN JAVA Java supports a special type of methods, called constructor that enables an object to initialize itself when it is created. Constructors have the same name as the class it-self. Constructors do not specify a return type, not even void. This is because they return the instance of the class itself. A constructor is automatically called when an object is created.
INTERNET TECHNOLOGY (CORE JAVA)
Syntax: Constructor_name([arguments]) { // body } Constructors are generally of two types. 1. Non-Parameterized 2. Parameterized Non-Parameterized
Prog. No.:- 33 // Non - parameterised constructor class Point1 { int x; int y; Point1() //constructor of class { x = 10; y = 20; } void display() { System.out.println("\n\n\t-----Printing the coordinates-----"); System.out.println("\t\t\t" + x + " " + y); } } class Point1Test { public static void main(String args[]) { Point1 p1 = new Point1(); // constructor will be call automatically from here p1.display();
Output: C:\java> javac Point1Test.java C:\java> java Point1Test -----Printing the coordinates----10 20
Parameterized
Prog. No.:- 34 // parameterised constructor import java.util.Scanner; class Point2 { int x; int y; Point2(int a, int b) { x = a; y = b; }
INTERNET TECHNOLOGY (CORE JAVA)
void display() { System.out.println("\n\n\t-----Printing the coordinates-----"); System.out.println("\t\t\t" + x + " " + y); } } class Point2Test { public static void main(String args[]) { int i,k; Scanner s = new Scanner(System.in); System.out.print("Enter int value for i : "); i = s.nextInt(); System.out.print("Enter int value for k : "); k = s.nextInt(); Point2 p1 = new Point2(i,k); p1.display(); } }
Output: C:\java> javac Point2Test.java C:\java> java Point2Test Enter int value for i : 10 Enter int value for k : 20 -----Printing the coordinates----10 20
KEYWORDS IN JAVA We are going to learn few regularly used keywords. 1. new 2. this 3. static 4. super 5. final
new: The new keyword dynamically allocates memory for an object. Syntax: claas_name object _name = new class_name(); EX. Box b1 = new Box(); Box b2 = new Box(); We have already seen so many programs in which we used new keyword for creating objects.
INTERNET TECHNOLOGY (CORE JAVA)
this: This keyword is the name of a reference that refers to a calling object itself. One common use of the this keyword is to reference a class` hidden data fields. We can have local variables, including formal parameters to methods which overlap with the names of the class` instance variables. The local variable hides the instance variable so we use this keyword. Another common use of this keyword is to enable a constructor to invoke another constructor of the same class. java requires that the this(arg-list) statement appear first in the constructor before any other statements.
Prog. No.:- 35 public class This_Test { public static void main(String[] args) { abc a1 = new abc(); //call non parameterize constructor } } class abc { int x,y; abc() { this(10,20); //this will call another constructor } abc(int x,int y) { this.x=x+5; //it will set class` member x this.y=y+5; //it will set class` member y System.out.println("local method`s x = " +x); System.out.println("local method`s y = " +y); Print_data(); } public void Print_data() { System.out.println("x = " +x); System.out.println("y = " +y); } }
Output : C:\java> javac This_Test.java C:\java> java This_Test local method`s x = 10 local method`s y = 20 x = 15 y = 25
static : A class member must be accessed with the use of an object of its class but sometimes we want to define a class member that will be used independently without creating any object of that class. It is possible in java to create a member that can be used by itself, without reference to a specific instance.
INTERNET TECHNOLOGY (CORE JAVA)
To create such a member, precede its declaration with the keyword static. When a member is declared static, it can be accessed before any objects of its class are created, and without reference to any object. One can declare both methods and variables to be static. The most common example of a static member is main(). Main () is declared as static because it must be called before any object exist. Instance variables declared as static are actually, global variables. When objects of its class are declared, no copy of a static variable is made. Instead, all instances of the class share the same static variable. Method declared as static have several restrictions: 1.
Can call only other static methods.
2.
Only access static data.
3.
Cannot refer to this or super in any way.
One can also declare a static block which gets executed exactly once, when the class is first loaded.
Prog. No.:- 36 public class Static_Test { public static void main(String[] args) { display(40); //call static method } static int i = 5; static int j; int k = 10; static void display(int a) { System.out.println("a = "+a); // here a = 40 System.out.println("i = "+i); // here i = 5 System.out.println("j = "+j); // here j = 50( because of static block j = i * 10 = 5 * 10 =50 ) //System.out.println("k = "+k); //can,t make a static reference to the nonstatic field k } static { System.out.println("Static block initialized.........."); j = i * 10; } }
Output : C:\java> javac Static_Test.java C:\java> java Static_Test Static block initialized.......... a = 40 i = 5 j = 50
super : super keyword is used to call a superclass constructor and to call or access super class members(instance variables or methods).
INTERNET TECHNOLOGY (CORE JAVA)
Syntax of super : => super(arg-list) When a subclass calls super() it is calling the constructor of its immediate superclass. super() must always be the first statement executed inside a subclass constructor. => super.member Member can be either method or instance variables. This second form of super is most applicable to situation in which member names of a subclass hide member of superclass due to same name.
Prog. No.:- 37 class A1 { public int i; A1() { i=5; } } class B1 extends A1 { int i; B1(int a,int b) { super(); //calling super class constructor //now we will change value of superclass variable i super.i=a; //accessing superclass member from subclass i=b; } void show() { System.out.println("i in superclass = " + super.i ); System.out.println("i in subclass = " + i ); } } public class Usesuper { public static void main(String[] args) { B1 b = new B1(10,12); b.show(); } }
Output : C:\java> javac Usesuper.java C:\java> java Usesuper i in superclass = 10 i in subclass = 12
The instance variable i in B1 hides the i in A, super allows access to the i defined in the superclass. Super can also be used to call methods that are hidden by a subclass.
INTERNET TECHNOLOGY (CORE JAVA)
final : final keyword can be use with variables, methods and class. => final variables When we want to declare constant variable in java we use final keyword. Syntax : final variable name = value; => final method Syntax: final methodname(arg) When we put final keyword before method than it becomes final method. To prevent overriding of method final keyword is used, means final method can‘t be override. => final class A class that can not be sub classed is called a final class. This is archived in java using the keyword final as follow. Any attempt to inherit this class will cause an error and compiler will not allow it. Syntax : final class class_name { ... }
Prog. No.:- 38 final class aa { final int a=10; public final void ainc() { a++; // The final field aa.a cannot be assigned } } class bb extends aa // The type bb cannot subclass the final class aa { public void ainc() //Cannot override the final method from aa { System.out.println("a = " + a); } } public class Final_Test { public static void main(String[] args) { bb b1 = new bb(); b1.ainc(); } } Output: C:\java> javac Final_Test.java Error:………………………….
INTERNET TECHNOLOGY (CORE JAVA)
Above program have no output will be there because all the comments in above program are errors. Remove final keyword from class than you will get error like final method can not be override
ACCESS CONTROL IN JAVA Access can control what parts of a program can access the member of a class. By controlling access, one can prevent misuse. Allowing access to data only through a well-defined set of methods, one can prevent misuse of that data. Thus, when correctly implemented, a class creates ―black box‖. How a member can be accessed is determined by the access specifier that modifies its declaration. Java provides a set to access specifiers. Some aspects of access control are related to inheritance or packages.
Java’s access specifiers are: public: o When a member of a class is specified by the public specifier, then that member can be accessed by any other code. o The public modifier makes a method or variable completely available to all classes. o when the class is defined as public, it can be accessed by any other class. private: o To hide a method or variable from other classes, private modifier is used. o A private variable can be used by methods in its own class but not by objects of any other class. o Neither private variables nor private methods are inherited by subclass. o The only place these variables and methods can be seen is from within their own class. protected: o protected applies only when inheritance is involved. o If we want to allow an element to be seen outside your current package, but only to classes that are inherited from our class directly, then declare that element as protected. default: o We have seen that when no access control modifier is specified, it is called as default access. o Classes written like this are not accessible in other package. o Any variable declared without a modifier can be read or changed by any other class in the same package. o Any method declared the same way can be called by any other class in the same package. o When a member does not have an explicit access specification, o It is visible to subclasses as well as to other classes in the same package.
The following table summarizes the levels of access control: Access From the same class From any class in the same package From any class outside the package
Public
Protected
Default
Private
Yes
Yes
Yes
Yes
Yes
Yes
Yes
No
Yes
No
No
No
INTERNET TECHNOLOGY (CORE JAVA)
From a sub - class in the same package From a sub - class outside the same package
Yes
Yes
Yes
No
Yes
Yes
Yes
No
METHOD OVERLOADING IN JAVA Method overloading: A class can contain any number of methods. Methods can be with parameter and without parameter. The parameter in a method are called type signature. It is possible in java to define two or more methods within the same class that share the same name, but with different parameter declarations (type signatures). When this is the case, the methods are said to be overloaded, and the process is referred to as method overloading. Overloading methods demonstrate the concept of polymorphism. When an overloaded method is invoked, java uses the type and/or number of arguments as its guide to determine which version of the overloaded method to call. Thus, overloaded methods must differ in the type and/or number of their parameters. Overloaded methods may have different return types. When java encounters a call to an overloaded method, it simply executes the version of the method whose parameters match the arguments used in the call.
Prog. No.:- 39 //METHOD OVERLOADING public class MethodOver { int n1; int n2; MethodOver() { n1 = 10; n2 = 20; } void square() { System.out.println("The Square is " + n1 * n2); } void square(int p1) { n1 = p1; System.out.println("The Square is " + n1 * n2); } void square(int p1, int p2) { n1 = p1; n2 = p2; System.out.println("The Square is " + n1 * n2); } public static void main(String args[]) { MethodOver obj1 = new MethodOver(); obj1.square(); //call non parameterise method obj1.square(4); //call method which has 1 argument obj1.square(7,8); //call method which has 2 argument } }
INTERNET TECHNOLOGY (CORE JAVA)
Output : C:\java> javac MethodOver.java C:\java> java MethodOver The Square is 200 The Square is 80 The Square is 56
We can see that there are 3 square methods with different argument. It’s called method overloading.
CONSTRUCTOR OVERLOADING IN JAVA Constructors having the same name with different parameter list is called constructor overloading.
Prog. No.:- 40 class Point { int x; int y; Point(int a, int b) { x = a; y = b; } } class Circle { int originX; int originY; int radius; //Default Constructor Circle() { originX = 5; originY = 5; radius = 3; } // Constructor initializing the coordinates of origin and the radius. Circle(int x1, int y1, int r) { originX = x1; originY = y1; radius = r; }
Circle(Point p, int r) { originX = p.x; originY = p.y;
INTERNET TECHNOLOGY (CORE JAVA)
radius = r; } void display() { System.out.println("--Center at " + originX + " and " + originY); System.out.println("Radius = " + radius); } public static void main(String args[]) { Circle c1 = new Circle(); Circle c2 = new Circle(10,20,5); Circle c3 = new Circle(new Point(15,25),10); c1.display(); c2.display(); c3.display(); } }
Output : C:\java> C:\java> --Center Radius = --Center Radius = --Center Radius =
javac Circle.java java Circle at 5 and 5 3 at 10 and 20 5 at 15 and 25 10
NOTE:- Above program is quite complicated here i am giving you perfect flow of program. First of all note one thing that new ClassName() this is a short syntax of creating object of any class. And we all know that when we create object the constructor of that class will be called automatically. So in our program first of all due to syntax Circle c1 = new Circle(); non parameterize constructor will be called for object c1 so we get output like Center at 5 and 5 Radius = 3 in c1.display(). Next due to syntax Circle c2 = new Circle(10,20,5); constructor which has 3 arguments will be called for object c2 so we get output like Center at 10 and 20 Radius = 5 in c2.display(). Now when we define object c3 our syntax is like Circle c3 = new Circle(new Point(15,25),10); so first of all it will create object for Point class so constructor of point class will be called and it will set parameter x and y. Then constructor of circle class which has Point class object as an argument along with one int argument will be called and set all parameter as per program and we get output like Center at 15 and 25 Radius = 10 in c3.display(). We can also write Point p1 = new Point(15,25); Circle c3 = new Circle(p1,10);
MORE ABOUT METHOD Passing Objects as a Parameter to Method. We have seen that methods can take parameters as input and process them. It is also common to pass objects as a parameter to methods.
INTERNET TECHNOLOGY (CORE JAVA)
Prog. No.:- 41 class PassObj { int n1; int n2; // constructor PassObj() { n1 = 0; n2 = 0; } PassObj(int p1, int p2) { n1 = p1; n2 = p2; } void multiply(PassObj p1) { int temp; temp = p1.n1 * p1.n2; System.out.println("Multiplication is " + temp); } public static void main(String args[]) { PassObj obj1 = new PassObj(5,6); PassObj obj2 = new PassObj(); obj2.multiply(obj1); } }
Output : C:\java> javac PassObj.java C:\java> java PassObj Multiplication is 30
Method overloading with object as a parameter.
Prog. No.:- 42 class MetObjOv { int n1; int n2; // constructor MetObjOv() { n1 = 0; n2 = 0; } MetObjOv(int x, int y) { n1 = x; n2 = y; } void multiply(MetObjOv p1) {
INTERNET TECHNOLOGY (CORE JAVA)
n1 = p1.n1; n2 = p1.n2; System.out.println("There is nothing to multiply "); System.out.println("n1 = "+n1+"\tn2 = " +n2); } void multiply(MetObjOv p1, MetObjOv p2) { n1 = p1.n1 * p2.n1; n2 = p1.n2 * p2.n2; System.out.println("Multiplication of two objects "); System.out.println("n1 = " + n1 + "\tn2 = " + n2 ); } public static void main(String args[]) { MetObjOv obj1 = new MetObjOv(5,6); MetObjOv obj2 = new MetObjOv(6,5); MetObjOv obj3 = new MetObjOv(); obj3.multiply(obj1); obj3.multiply(obj1, obj2); } }
Output : C:\java> javac MetObjOv.java C:\java> java MetObjOv There is nothing to multiply n1 = 5 n2 = 6 Multiplication of two objects n1 = 30 n2 = 30
Return an Object. A method can return any type of data, including class type (object) that you create.
Prog. No.:- 43 class RetObj { int n1; int n2; // constructor RetObj() { n1 = 0; n2 = 0; } RetObj(int x, int y) { n1 = x; n2 = y; } RetObj multiply(RetObj p1, RetObj p2) { n1 = p1.n1 * p2.n1; n2 = p1.n2 * p2.n2; return (this); } void display() { System.out.println("An Example of returning an Object ");
INTERNET TECHNOLOGY (CORE JAVA)
System.out.println("n1 = "+n1+"\tn2 = " +n2); } public static void main(String args[]) { RetObj obj1 = new RetObj(5,6); RetObj obj2 = new RetObj(6,5); RetObj obj3 = new RetObj(); obj3 = obj3.multiply(obj1, obj2); obj3.display(); } }
Output : C:\java> javac RetObj.java C:\java> java RetObj An Example of returning an Object n1 = 30 n2 = 30
RetObj multiply(RetObj p1, RetObj p2) This is the syntax in our program which has return type object. obj3 = obj3.multiply(obj1, obj2); this is the syntax which calls method multiply and return object, it will store in obj3.
THERE ARE TWO TYPES OF CALLING METHOD AND THOSE ARE 1. call by value 2. call by reference CALL BY VALUE In call by value when we call any method we pass value as method parameter so changing in local variables of the method doesn't`t affect the original variables of class.This method copies the value of an argument into the formal parameter of the subroutine. Therefore, changes made to the parameter of the subroutine have no effect on the argument. In java, when we pass a primitive type to a method, it is passed by value. Thus, what occurs to the parameter that receives the argument has no effect outside the method.
Prog. No.:- 44 class Value { int a,b; Value(int i,int j) { a = i ; b = j; } void call(int a, int b) { a = a * 2; b = b * 2; } } public class CallBy_Value
INTERNET TECHNOLOGY (CORE JAVA)
{ public static void main(String[] args) { Value v = new Value(10,20); System.out.println("a and b before call............"); System.out.println("a = "+v.a); System.out.println("b = "+v.b); v.call(v.a,v.b); // CALL BY VALUE System.out.println("a and b after call............"); System.out.println("a = "+v.a); System.out.println("b = "+v.b); } }
Output : C:\java> javac CallBy_Value.java C:\java> java CallBy_Value a and b before call............ a = 10 b = 20 a and b after call............ a = 10 b = 20
We can see that after calling method we change value of a and b but it will not affect the original value of class` members because of call by value. We pass value v.a and v.b as parameter and it will change local method`s a and b variables. Call by reference : We pass reference as parameter in function calling. We all know that reference means object so we pass object as parameter. A reference to an argument (not value of argument) is passed to the parameter. Inside the subroutine, this reference is used to access the actual argument specified in the call. This means that changes made to the parameters will affect the argument used to call the subroutine. When we pass an object to a method, the situation changes, because objects are passed by call-by-reference. When we create a variable of a class type, we are only creating a reference to an object. Thus, when you pass this reference to a method, the parameter that receives it will refer to the same object as that referred to by the argument. This effectively means that objects are passed to method do affect the object used as an argument.
Prog. No.:- 45 class Reference { int a,b; Reference(int i,int j) { a = i ; b = j; } void call(Reference r) { r.a = a * 2; r.b = b * 2; } }
INTERNET TECHNOLOGY (CORE JAVA)
public class CallBy_Reference { public static void main(String[] args) { Reference r = new Reference(10,20); System.out.println("a and b before call............"); System.out.println("a = "+r.a); System.out.println("b = "+r.b); r.call(r); // CALL BY REFERENCE System.out.println("a and b after call............."); System.out.println("a = "+r.a); System.out.println("b = "+r.b); } }
Output : C:\java> javac Reference.java C:\java> java Reference a and b before call............ a = 10 b = 20 a and b after call............. a = 20 b = 40
We can see that after calling method value of original a and b is changed because of call by reference. We pass "r" reference (Object) as parameter in method calling. So changes inside method will affect original variable of class.
RECURSION Recursion is the process of defining something in terms of itself. When function calls itself is called recursion. A method that calls itself is said to be recursive.
Prog. No.:- 46 import java.util.Scanner;
class Factorial { // this is a recursive function int fact(int n) { int result; if(n==1) return 1; result = fact(n-1) * n; //From here function call it self (fact(n-1)) return result; } } public class Recursion { public static void main(String args[]) { int x;
INTERNET TECHNOLOGY (CORE JAVA)
Scanner s = new Scanner(System.in); System.out.print("Enter int no = "); x = s.nextInt(); Factorial f = new Factorial(); System.out.println("Factorial of" + x + " is " + f.fact(x)); } }
Output : C:\java> javac Recursion.java C:\java> java Recursion Enter int no = 7 Factorial of7 is 5040
The method fact is recursive because it calls itself.The whole precess something like this result = fact(7-1) * 7 and so on until it returns 1. So one thing is sure that we have to take care that in every recursive process there must be a terminate condition to come out from recursion.
NESTED CLASS It is possible to define a class within another class; such classes are known as nested classes. The scope of a nested class is bounded by the scope of its enclosing class. That means, if class B is defined within class A, then B is known to A, but not outside A. If A is nesting class B, then A has access to all the members of B, including private members. But the B does not have access to the members of nested class. There are two types of nested classes: 1. Static 2. Non – Static Static nested class A static nested class is one which has the static modifier, as it is static it must access the member of its enclosing class through an object. That means it cannot refer to member of its enclosing class directly.
Non – Static nested class Non – Static nested class is known as inner class. It has access to all of its variables and methods of its outer class and can refer to them directly. An inner class is fully within the scope of its enclosing class.
Prog. No.:- 47 class InnerTest { class Contents { private int i = 16; public int value()
INTERNET TECHNOLOGY (CORE JAVA)
{ return i; } } class Destination { private String label; Destination(String whereTo) { label = whereTo; } } public void ship(String dest) { Contents c = new Contents(); // create object of inner class Contents Destination d = new Destination(dest); // create object of inner class Destination System.out.println("Shipped " + c.value() + " item(s) to " + dest); } public static void main(String args[]) { Inner1 p = new Inner1(); p.ship("Congo"); //call ship method of outer class "inner1" } }
Output : C:\java> javac InnerTest.java C:\java> java InnerTest Shipped 16 item(s) to Congo
Let us see one more example
Prog. No.:- 48 class OuterTest { int outer_x = 100; void test() { Inner inner = new Inner(); inner.display(); } // this is an inner class class Inner { int y = 10; // y is local to Inner void display() { System.out.println("display: outer_x = " + outer_x); } } void showy() { System.out.println(y); // error, y not known here!
INTERNET TECHNOLOGY (CORE JAVA)
} } class InnerClassDemo { public static void main(String args[]) { Outer outer = new Outer(); outer.test(); } }
Here, y is declared as an instance variable of Inner. Thus it is not known outside of that class and it cannot be used by showy( ).
COMMAND LINE ARGUMENT We will want to pass information into a program when you run it. This is accomplished by passing command-line arguments to main( ). A command-line argument is the information that directly follows the program‘s name on the command line when it is executed. To access the command-line arguments inside a Java program is quite easy—they are stored as strings in the String array passed to main( ).
Prog. No.:- 49 class CommandLine { public static void main(String args[]) { for(int i=0; i < args.length; i++) System.out.println("args[" + i + "]: " +args[i]); } }
Try executing this program, as shown here: java CommandLine this is a test 100 -1 When you do, you will see the following output: args[0]: this args[1]: is args[2]: a args[3]: test args[4]: 100 args[5]: -1 But first of all you should have the basic knowledge about command line and how any java program run through command prompt.
INHERITANCE IN JAVA Inheritance :
INTERNET TECHNOLOGY (CORE JAVA)
The derivation of one class from another class is called Inheritance. A class that is inherited is called a superclass. The class that does the inheriting is called as subclass. A subclass inherits all instance variables and methods from its superclass and also has its own variables and methods. One can inherit the class using keyword extends. Syntax : Class subclass-name extends superclass-name { // body of class. } In java, a class has only one super class. Java does not support Multiple Inheritance. One can create a hierarchy of inheritance in which a subclass becomes a superclass of another subclass. However, no class can be a superclass of itself.
Prog. No.:- 50 class A //superclass { int num1; //member of superclass int num2; //member of superclass void setVal(int no1, int no2) //method of superclass { num1 = no1; num2 = no2; } } class B extends A //subclass B { int multi; //member of subclass void mul() //method of subclass { multi = num1*num2; //accessing member of superclass from subclass } } class InheritTest { public static void main(String args[]) { B subob = new B(); subob.setVal(5,6); //calling superclass method throgh subclass object subob.mul(); System.out.println("Multiplication is " + subob.multi); } }
Output : C:\java> javac InheritTest.java C:\java> java InheritTest Multiplication is 30
INTERNET TECHNOLOGY (CORE JAVA)
Note : Private members of super class is not accessible in subclass, super class is also called parent class or base class, subclass is also called child class or derived class.
Method Overriding: Defining a method in the subclass that has the same name, same arguments and same return type as a method in the super class and it hides the super class method is called method overriding. Now when the method is called, the method defined in the subclass is invoked and executed instead of the one in the super class.
Prog. No.:- 51 class Xsuper { int y; Xsuper(int y) { this.y=y; } void display() { System.out.println("super y = " +y); } } class Xsub extends Xsuper { int z; Xsub(int z , int y) { super(y); this.z=z; } void display() { System.out.println("super y = " +y); System.out.println("sub z = " +z); } } public class TestOverride { public static void main(String[] args) { Xsub s1 = new Xsub(100,200); s1.display(); } }
Output : C:\java> javac TestOverride.java C:\java> java TestOverride super y = 200 sub z = 100
The method display () defined in the subclass is invoked.
INTERNET TECHNOLOGY (CORE JAVA)
Overloading VS Overriding:
Method overloading is compile time polymorphism. Method overriding is run time polymorphism. Overloading a method is a way to provide more than one method in one class which has same name but different argument to distinguish them. Defining a method in the subclass that has the same name, same arguments and same return type as a method in the super class is called method overriding.
MULTILEVEL INHERITANCE IN JAVA Prog. No.:- 52 class Student { int rollno; String name; student(int r, String n) { rollno = r; name = n; } void dispdatas() { System.out.println("Rollno = " + rollno); System.out.println("Name = " + name); } } class Marks extends Student { int total; marks(int r, String n, int t) { super(r,n); //call super class (student) constructor total = t; } void dispdatam() { dispdatas(); // call dispdatap of student class System.out.println("Total = " + total); } } class Percentage extends Marks { int per; percentage(int r, String n, int t, int p) { super(r,n,t); //call super class(marks) constructor per = p; } void dispdatap() { dispdatam(); // call dispdatap of marks class System.out.println("Percentage = " + per); }
INTERNET TECHNOLOGY (CORE JAVA)
} class Multi_Inherit { public static void main(String args[]) { percentage stu = new percentage(1912, "SAM", 350, 50); //call constructor percentage stu.dispdatap(); // call dispdatap of percentage class } }
Output : C:\java> javac Multi_Inherit.java C:\java> java Multi_Inherit Rollno = 1912 Name = SAM Total = 350 Percentage = 50
It is common that a class is derived from another derived class. The class student serves as a base class for the derived class marks, which in turn serves as a base class for the derived class percentage. The class marks is known as intermediated base class since it provides a link for the inheritance between student and percentage. The chain is known as inheritance path. When this type of situation occurs, each subclass inherits all of the features found in all of its super classes. In this case, percentage inherits all aspects of marks and student. To understand the flow of program read all comments of program. Q:- When a class hierarchy is created, in what order are the constructors for the classes that make up the hierarchy called? Ans: Constructors are called in order of derivation, from super class to subclass. Further, since super ( ) must be the first statement executed in a subclass‘ constructor, this order is the same whether or not super ( ) is used. If super ( ) is not used, then the default or parameter less constructor of each super class will be executed. As you can see from the output the constructors are called in order of derivation. If you think about it, it makes sense that constructors are executed in order of derivation. Because a super class has no knowledge of any subclass, any initialization it needs to perform is separate from and possibly prerequisite to any initialization performed by the subclass. Therefore, it must be executed first
Prog. No.:- 52 class X { X() { System.out.println("Inside X's constructor."); } } class Y extends X // Create a subclass by extending class A. { Y() { System.out.println("Inside Y's constructor."); } } class Z extends Y {
// Create another subclass by extending B.
INTERNET TECHNOLOGY (CORE JAVA)
Z() { System.out.println("Inside Z's constructor."); } } public class CallingCons { public static void main(String args[]) { Z z = new Z(); } }
Output: C:\java> javac CallingCons.java C:\java> java CallingCons Inside X's constructor. Inside Y's constructor. Inside Z's constructor.
DYNAMIC METHOD DISPATCH Dynamic Method Dispatch: Dynamic method dispatch is the mechanism by which a call to an overridden method is resolved at run time, rather than compile time. Dynamic method dispatch is important because this is how Java implements run-time polymorphism. Method to execution based upon the type of the object being referred to at the time the call occurs. Thus, this determination is made at run time. In other words, it is the type of the object being referred to (not the type of the reference variable) that determines which version of an overridden method will be executed.
Prog. No.:- 53 class A { void callme() { System.out.println("Inside A's callme method"); } } class B extends A { // override callme() void callme() { System.out.println("Inside B's callme method"); } } class C extends A { // override callme() void callme() { System.out.println("Inside C's callme method"); } }
INTERNET TECHNOLOGY (CORE JAVA)
public class Dynamic_disp { public static void main(String args[]) { A a = new A(); // object of type A B b = new B(); // object of type B C c = new C(); // object of type C A r; // obtain a reference of type A r = a; // r refers to an A object r.callme(); // calls A's version of callme r = b; // r refers to a B object r.callme(); // calls B's version of callme r = c; // r refers to a C object r.callme(); // calls C's version of callme } }
Output : C:\java> javac Dynamic_disp.java C:\java> java Dynamic_disp Inside A's callme method Inside B's callme method Inside C's callme method
Reference of type A, called r, is declared. The program then assigns a reference to each type of object to r and uses that reference to invoke callme( ). As the output shows, the version of callme( ) executed is determined by the type of object being referred to at the time of the call. Abstract Classes : When the keyword abstract appears in a class definition, it means that zero or more of its methods are abstract. An abstract method has no body. Some of the subclass has to override it and provide the implementation. Objects cannot be created out of abstract class. Abstract classes basically provide a guideline for the properties and methods of an object. In order to use abstract classes, they have to be sub classed. There are situations in which you want to define a super class that declares the structure of a given abstraction without providing a complete implementation of every method. That is, sometimes you want to create a super class that only defines generalized form that will be shared by all of its subclasses, leaving it to each subclass to fill in the details. One way this situation can occur is when a super class is unable to create a meaningful implementation for a method. Syntax : abstract type name(parameter-list); As you can see, no method body is present. Any class that contains one or more abstract methods must also be declared abstract. To declare a class abstract, you simply use the abstract keyword in front of the class keyword at the beginning of the class declaration. There can be no objects of an abstract class. That is, an abstract class cannot be directly instantiated with the new operator. Any subclass of an abstract class must either implement all of the abstract methods of the super class, or be itself declared abstract.
Prog. No.:- 54 abstract class shape
INTERNET TECHNOLOGY (CORE JAVA)
{ double dim1; double dim2; shape(double a, double b) { dim1 = a; dim2 = b; } abstract double area(); } class rectangle extends shape { rectangle(double a, double b) { super(a,b); } double area() { System.out.println("Area of rectangle."); return dim1*dim2; } } class triangle extends shape { triangle(double a, double b) { super(a,b); } double area() { System.out.println("Area of triangle."); return dim1*dim2/2; } } public class AbstractTest { public static void main(String args[]) { rectangle r = new rectangle(10,20); triangle t = new triangle(10,6); System.out.println(r.area()); System.out.println(t.area()); } }
Output: C:\java> javac AbstractTest.java C:\java> java AbstractTest Area of rectangle. 200.0 Area of triangle. 30.0
OBJECT CLASS Object class: There is one special class, Object, defined by Java. All other classes are subclasses of Object. That is, Object is a super class of all other classes. This means that a reference variable of type
INTERNET TECHNOLOGY (CORE JAVA)
Object can refer to an object of any other class. Every class in java is descended from the java.lang.Object class. If no inheritance is specified when a class is defined, the super class of the class is Object by default. public class circle { ... } is equivalent to public class circle extends Object { ... }. Methods of Object class METHOD
PURPOSE
boolean equals(Object obj_name)
Creates a new object that is the same as the object being cloned. Determines whether one object is equal to another
Void finalize()
Called before an unused object is recycled
Class getClass( )
Obtains the class of an object at run time.
Object clone()
Returns the hash code associated with the invoking object. Resumes execution of a thread waiting on the invoking object. Resumes execution of all threads waiting on the invoking object. Returns a string that describes the object.
int hashCode( ) void notify( ) void notifyAll( ) String toString( ) void wait( ) void wait(long milliseconds)
Waits on another thread of execution.
void wait(long milliseconds, int nanoseconds) The methods getclass(), notify(), notifyall() and wait() are declared as final. We may override the others.
tostring() ?public String tostring(). It returns a String that describes an object. ?It consisting class name, an at (@) sign and object memory address in hexadecimal. EX : Circle c1 = new Circle(); System.out.println(c1.tostring()); It will give O/P like Circle@15037e5 We can also write System.out.println(c1);
POLYMORPHISM Polymorphism:
INTERNET TECHNOLOGY (CORE JAVA)
An object of a sub class can be used whenever its super class object is required. This is commonly known as polymorphism. In simple terms polymorphism means that a variable of super type can refer to a sub type object.
Fig. 4(Polymorphism)
JAVA INTERFACE Java Interface: Interfaces are similar to abstract classes, but differ in their functionality. In interfaces, none of the methods are implemented means interfaces defines methods without body. Interfaces are syntactically similar to classes, but they lack instance variables, and their methods are declared without any body. But, it can contain final variables, which must be initialized with values. Once it is defined, any number of classes can implement an interface. One class can implement any number of interfaces. If we are implementing an interface in a class we must implement all the methods defined in the interface as well as a class can also implement its own methods. Interfaces add most of the functionality that is required for many applications which would normally resort to using multiple inheritances in C++.
INTERNET TECHNOLOGY (CORE JAVA)
Defining interfaces in java with syntax: Syntax : [Access-specifier] interface interface-name { Access-specifier return-type method-name(parameter-list); final type var1=value; } Where, Access-specifier is either public or it is not given. When no access specifier is used, it results into default access specifier and if interface has default access specifier then it is only available to other members of the same package. When it is declared as public, the interface can be used by any other code of other package. Interface-Name: name of an interface, it can be any valid identifier. The methods which are declared having no bodies they end with a semicolon after the parameter list. Actually they are abstract methods; Any class that includes an interface must implement all of the methods. Variables can be declared inside interface declarations. They are implicitly final and static, means they cannot be changed by implementing it in a class. They must also be initialized with a constant value. EX : interface Item { static final int code = 100; static final String name = "Fan"; void display ( ); } interface Area { static final float pi = 3.14F; float compute ( float x, float y ); void show ( ); }
Implementing interfaces Once an interface has been defined, one or more classes can implement that interface. To implement an interface, include the implements clause in a class definition, and then create the methods declared by the interface. The general form of a class that includes the implements clause looks like this: Access-specifier class classname [extends superclass] [implements interface, [, interface..]] { // class body } If a class implements from more than one interface, names are separated by comma.
INTERNET TECHNOLOGY (CORE JAVA)
If a class implements two interfaces that declare the same method, then the same method will be used by clients of either interface. The methods that implement an interface must be declared as public. The type-signature of implementing method must match exactly the type signature specified in the interface.
Prog. No.:- 55 interface religion { String city = new String("Shimla"); void greet(); void pray(); } class gs implements religion { public void greet() { System.out.println("We greet – B.Tech 4th yr"); } public void pray() { System.out.println("We pray at " + city + "SummerHill "); } } class IfaceTest { public static void main(String args[]) { gs s = new gs(); s.greet(); s.pray(); } }
Output : C:\java> javac IfaceTest.java C:\java> java IfaceTest We greet – B.Tech 4th yr. We pray at Shimla SummerHill
Implementing interface having common function name Prog. No.:- 56 interface i1 { void disp(); } interface i2 { void disp(); } class c implements i1, i2
INTERNET TECHNOLOGY (CORE JAVA)
{ public void disp() { System.out.println("This is display .. "); } } class IfaceTest7 { public static void main(String args[]) { c cobj = new c(); cobj.disp(); } }
Output : C:\java> javac IfaceTest7.java C:\java> java IfaceTest7 This is display ..
Note : When implementing an interface method, it must be declared as public. It is possible for classes that implement interfaces to define additional members of their own. Partial Implementation of Interface : If we want to implement an interface in a class we have to implement all the methods defined in the interface. But if a class implements an interface but does not fully implement the method defined by that interface, then that class must be declared as abstract.
Prog. No.:- 57 interface i1 { void disp1(); void disp2(); } abstract class c1 implements i1 { public void disp1() { System.out.println("This is display of 1"); } } class c2 extends c1 { public void disp2() { System.out.println("This is display of 2"); } } class IfaceTest9 { public static void main(String args[])
INTERNET TECHNOLOGY (CORE JAVA)
{ c2 c2obj = new c2(); c2obj.disp1(); c2obj.disp2(); } }
Output : C:\java> javac IfaceTest9.java C:\java> java IfaceTest9 This is display of 1 This is display of 2
Accessing interface variable: Once can declare variable as object references that uses an interface rather than a class type. When you call a method through one of these references, the correct version will be called based on the actual instance of the interface being referred to.
Prog. No.:- 58 interface AreaCal { final double pi = 3.14; double areacalculation(double r); } class Circle implements AreaCal { public double areacalculation(double r) { double ar; ar = pi*r*r; return ar; } } class IfaceTest09 { public static void main(String args[]) { double area; AreaCal ac = new Circle(); ar = ac.areacalculation(10.25); System.out.println("Area of Circle is : " + ar); } }
Output : C:\java> javac IfaceTest09.java C:\java> java IfaceTest09 Area of Circle is : 329.89625
Here variable ac is declared to be of the interface type AreaCal, it was assigned an instance of circle. Although ac can be used to access the areacalculation() method, it cannot access any other members of the client class. An interface reference variable only has knowledge of the method declared by its interface declaration.
INTERNET TECHNOLOGY (CORE JAVA)
Extending interfaces: One interface can inherit another by use of the keyword extends. The syntax is the same as for inheriting classes. When a class implements an interface that inherits another interface, It must provide implementation of all methods defined within the interface inheritance. Note: Any class that implements an interface must implement all methods defined by that interface, including any that inherited from other interfaces.
Prog. No.:- 59 interface if1 { void dispi1(); } interface if2 extends if1 { void dispi2(); } class cls1 implements if2 { public void dispi1() { System.out.println("This is display of i1"); } public void dispi2() { System.out.println("This is display of i2"); } } public class Ext_ IfaceTest { public static void main(String args[]) { cls1 c1obj = new cls1(); c1obj.dispi1(); c1obj.dispi2(); } }
Output : C:\java> javac Ext_ IfaceTest.java C:\java> java Ext_ IfaceTest This is display of i1 This is display of i2
Note : We have to define disp1() and disp2() in cls1.
Multiple inheritance using interface..
Prog. No.:- 60 INTERNET TECHNOLOGY (CORE JAVA)
class stu { int rollno; String name = new String(); int marks; stu(int r, String n, int m) { rollno = r; name = n; marks = m; } } interface i { void display(); } class studerived extends stu implements i { studerived(int r, String n, int m) { super(r,n,m); } public void display() { System.out.println("Displaying student details .. "); System.out.println("Rollno = " + rollno); System.out.println("Name = " + name); System.out.println("Marks = " + marks); } } public class Multi_inhe_Test { public static void main(String args[]) { studerived obj = new studerived(1912, "Ram", 75); obj.display(); } }
Output : C:\java> javac Multi_inhe_Test.java C:\java> java Multi_inhe_Test Displaying student details .. Rollno = 1912 Name = Ram Marks = 75
INTERNET TECHNOLOGY (CORE JAVA)
Fig. 5(INTERFACE IMPLEMENTATION)
PACKAGES IN JAVA Java inbuilt packages: Package: Packages are java`s way of grouping a variety of classes and/or interfaces together. Java API packages: Java API provides a large number of classes grouped into different packages according to functionality.
Syntax for import packages: import packagename.classname; or
INTERNET TECHNOLOGY (CORE JAVA)
import packagename.*; These are known as import statements and must appear at the top of the file, before any file declaration as you can see in our few examples. Here import is a keyword. The first statement allows the specified class in the specified package to be imported. EX : import java.awt.Color; double y = java.lang.Math.sqrt(x); //lang is a package, Math is a class and sqrt is a method. For create new package you can write... package firstPackage; public class Firstclass { .................. body of class ................. }
Vector class:
The Vector class is one of the most important in all of the Java class libraries. We cannot expand the size of a static array. We may think of a vector as a dynamic array that automatically expands as more elements are added to it. All vectors are created with some initial capacity. When space is needed to accommodate more elements, the capacity is automatically increased. That is why vectors are commonly used in java programming.
This class provides the following constructors:
Vector() Vector(int n) Vector(int n, int delta) The first form creates a vector with an initial capacity of ten elements. The second form creates a vector with an initial capacity of n elements. The third form creates a vector with an initial capacity of n elements that increases by delta elements each time it needs to expand.
Prog. No.:- 61 import java.util.*; public class Vector_Test { public static void main(String args[]) { int i; Vector_Test v = new Vector_Test(); v.addElement(new Integer(10)); v.addElement(new Float(5.5f)); v.addElement(new String("Hi")); v.addElement(new Long(2500)); v.addElement(new Double(23.25)); System.out.println(v); String s = new String("Internet");
INTERNET TECHNOLOGY (CORE JAVA)
v.insertElementAt(s,1); System.out.println(v); v.removeElementAt(2); System.out.println(v); for(i=0;i<5;i++) { System.out.println(v.elementAt(i)); } } }
Output : C:\java> javac Vector_Test.java C:\java> java Vector_Test Internet Hi 2500 23.25
Random class:
The Random class allows you to generate random double, float, int, or long numbers. This can be very helpful if you are building a simulation of a real-world system. This class provides the following constructors. Random() Random(long start)
Here, start is a value to initialize the random number generator. Method Double nextDouble() Float nextFloat() Double nextGaussian() Int nextInt() Long nextLong()
Description Returns a random double value. Returns a random float value. Returns a random double value. Numbers obtained from repeated calls to this method have a Gaussian distribution with a mean of 0 and a standard deviation of 1. Returns a random int value. Returns a random long value.
Prog. No.:- 62 import java.util.*; public class Random_Test { public static void main(String args[]) { Random_Test ran = new Random_Test(); for(int i = 0; i<5;i++) { System.out.println(ran.nextInt());
INTERNET TECHNOLOGY (CORE JAVA)
} } }
Output: C:\java> javac Random_Test.java C:\java> java Random_Test 64256704 1265771787 -1962940029 1372052
Date class: The Date classes encapsulate information about a specific date and time. It provides the following constructors. Date() Date(long msec)
Here, the first form returns an object that represent the current date and time. The second form returns an object that represents the date and time msec in milliseconds after the time.
The time is defined as midnight on January 1,1970 GMT (Greenwich Mean Time). Method Boolean after(Date d) Boolean before(Date d) Boolean equals(Date d) Long getTime() Void setTime
Description Returns true if d is after the current date. Otherwise, returns false. Returns true if d is before the current date. Otherwise, returns false. Returns true if d has the same value as the current date. Otherwise, returns false. Returns the number of milliseconds since the epoch. Sets the date and time of the current object to represent msec milliseconds since the epoch.
(long msec) String toString()
Returns the string equivalent of the date.
Prog. No.:- 63 import java.util.*; public class Date_Test { public static void main(String args[]) { Date_Test dt = new Date_Test(); System.out.println(dt);
INTERNET TECHNOLOGY (CORE JAVA)
Date_Test epoch = new Date_Test(0); System.out.println(epoch); } }
Output : C:\java> javac Date_Test.java C:\java> java Date_Test Thu Sep 05 05:04:06 IST 2013 Thu Jan 01 05:30:00 IST 1970
Prog. No.:- 64 import java.util.Date; public class date2_Test { public static void main(String[] args) { Date d1 = new Date(); try { Thread.sleep(1000); } catch(Exception e){} Date d2 = new Date(); System.out.println("First Date : " + d1); System.out.println("Second Date : " + d2); System.out.println("Is second date after first ? : " + d2.after(d1)); } }
Output : C:\java> javac Date2_Test.java C:\java> java Date_Test2 First Date : Thu Sep 05 05:06:46 IST 2013 Second Date : Thu Sep 05 05:06:47 IST 2013 Is second date after first ? : true
Calendar & Gregorian class: The Calendar class allows you to interpret date and time information. This class defines several integer constants that are used when you get or set components of the calendar. These are listed here. AM AUGUST DAY_OF_WEEK DECEMBER FEBRUARY HOUR JULY
AM_PM APRIL DATE DAY_OF_MONTH DAY_OF_WEEK_IN_MONTH DAY_OF_YEAR DST_OFFSET ERA FIELD_COUNT FRIDAY HOUR_OF_DAY JANUARY JUNE MARCH
INTERNET TECHNOLOGY (CORE JAVA)
MAY MONDAY OCTOBER SECOND THURSDAY WEDNESDAY
MILLISECOND MONTH PM SEPTEMBER TUESDAY WEEK_OF_MONTH
YEAR
ZONE_OFFSET
MINUTE NOVEMBER SATURADAY SUNDAY UNDERIMBER WEEK_OF_YEAR The Calendar class does not have public constructors. Instead, you may use the static getInstance() method to obtain a calendar initialized to the current date and time.
Calendar getInstance()
Prog. No.:- 65 import java.util.Calendar; public class Cal_Test { public static void main(String[] args) { Calendar cal = Calendar.getInstance(); System.out.println("DATE is : " + cal.get(cal.DATE)); System.out.println("YEAR is : " + cal.get(cal.YEAR)); System.out.println("MONTH is : " + cal.get(cal.MONTH)); System.out.println("DAY OF WEEK is : " + cal.get(cal.DAY_OF_WEEK)); System.out.println("WEEK OF MONTH is : " + cal.get(cal.WEEK_OF_MONTH)); System.out.println("DAY OF YEAR is : " + cal.get(cal.DAY_OF_YEAR)); System.out.println("DAY OF MONTH is : " + cal.get(cal.DAY_OF_MONTH)); System.out.println("WEEK OF YEAR is : " + cal.get(cal.WEEK_OF_YEAR)); System.out.println("HOUR is : " + cal.get(cal.HOUR)); System.out.println("MINUTE is : " + cal.get(cal.MINUTE)); System.out.println("SECOND is : " + cal.get(cal.SECOND)); System.out.println("DAY OF WEEK IN MONTH is : " + cal.get(cal.DAY_OF_WEEK_IN_MONTH)); System.out.println("Era is : " + cal.get(cal.ERA)); System.out.println("HOUR OF DAY is : " + cal.get(cal.HOUR_OF_DAY)); System.out.println("MILLISECOND : " + cal.get(cal.MILLISECOND)); System.out.println("AM_PM : " + cal.get(cal.AM_PM));// Returns 0 if AM and 1 if PM } }
Output : C:\java> javac Cal_Test.java C:\java> java Cal_Test DATE is : 23 YEAR is : 2012 MONTH is : 9 DAY OF WEEK is : 3 WEEK OF MONTH is : 4 DAY OF YEAR is : 297 DAY OF MONTH is : 23 WEEK OF YEAR is : 43
INTERNET TECHNOLOGY (CORE JAVA)
HOUR is : 2 MINUTE is : SECOND is : DAY OF WEEK Era is : 1 HOUR OF DAY MILLISECOND AM_PM : 1
32 32 IN MONTH is : 4 is : 14 : 595
The GregorianCalendar class is a subclass of Calendar. It provides the logic to manage date and time information according to the rules of the Gregorian calendar. This class provides following constructors: GregorianCalendar() GregorianCalendar(int year, int month, int date) GregorianCalendar(int year, int month, int date, int hour, int minute, int sec) GregorianCalendar(int year, int month, int date, int hour, int minute) The first form creates an object initialized with the current date and time. The other forms allow you to specify how various date and time components are initialized. The class provides all of the method defined by Calendar and also adds the isLeapYear() method shown here: Boolean isLeapYear() This method returns true if the current year is a leap year. Otherwise, it returns false.
Math Class:
For scientific and engineering calculations, a variety of mathematical functions are required. Java provides these functions in the Math class available in java.lang package. The methods defined in Math class are given following: Method Double sin(double x) Double cos(double x) Double tan(double x) Double asin(double x) Double acos(double x) Double atan(double x) Double exp(double x) Double log(double x) Double pow(double x, double y) Double sqrt(double x) Int abs(double n) Double ceil(double x) Double floor(double x) Int max(itn n, int m) Int min(int n, int m)
Description Returns the sine value of angle x in radians. Returns the cosine value of the angle x in radians Returns the tangent value of the angle x in radians Returns angle value in radians for arcsin of x Returns angle value in radians for arcos of x Returns angle value in radians for arctangent of x Returns exponential value of x Returns the natural logarithm of x Returns x to the power of y Returns the square root of x Returns absolute value of n Returns the smallest wholoe number greater than or equal to x Returns the largest whole number less than or equal to x Returns the maximum of n and m Returns the minimum of n and m
INTERNET TECHNOLOGY (CORE JAVA)
Double rint(double x) Int round(float x) Long round(double x) Double random() Double toRandians(double angle) Double toDegrees(double angle)
Returns the rounded whole number of x Returns the rounded int value of x Returns the rounded int value of x Returns a random value between 0 and 1.0 Converts the angle in degrees to radians Converts the angle in radians to degrees
Prog. No.:- 66 public class Angles { public static void main(String args[]) { double theta = 120.0; System.out.println(theta + " degrees is " + Math.toRadians(theta) + " radians."); theta = 1.312; System.out.println(theta + " radians is " + Math.toDegrees(theta) + " degrees."); } }
Output : C:\java> javac Angles.java C:\java> java Angles 120.0 degrees is 2.0943951023931953 radians. 1.312 radians is 75.17206272116401 degrees.
Hashtable : Hashtable is a part of the java.util library and is a concrete implementation of a dictionary. (Dictionary is a class that represents a key/value storage repository. Given a key and value, you can store the value in a Dictionary object. Once the value is stored, you can retrieve it by using its key.) Hashtable stores key/value pairs in a hash table. When using a Hashtable, you specify an object that is used as a key, and the value that you want to link to that key. The key is then hashed, and the resulting hash code is used as the index at which the value is stored within the table. The Hashtable constructors are shown here: Hashtable() Hashtable(int size) The first constructor is the default constructor. The second constructor creates a hash table that has an initial size specified by size. The methods available with Hashtable are Method Void clear() Boolean containsKey(Object key)
Boolean containsValue(Object value)
Description Resets and empties the hash table. Returns true if some key equals to key exists within the hash table. Returns false if the key isn‘t found. Returns true if some value equal to value exists within the hash table. Returns false if the value isn‘t found.
INTERNET TECHNOLOGY (CORE JAVA)
Enumeration elements( ) Object get(Object key) Boolean isEmpty( ) Enumeration keys( ) Object put(Object key Object value) Object remove(Object key) Int size( ) String toString( )
Returns an enumeration of the values contained in the hash table. Returns the object that contains the value associated with key. If key is not in the hash table, a null object is returned. Returns true if the hash table is empty; Returns false if it contains at least one key. Returns an enumeration of the keys contained in the hash table. Inserts a key and a value into the hash table. Removes key and its value. Returns the value associated with key. If key is not in the hash table, a null object is returned. Returns the number of entries in the hash table. Returns the string equivalent of a hash table.
Prog. No.:- 67 import java.util.*; public class hash1 { public static void main(String args[]) { Hashtable marks = new Hashtable(); Enumeration names; Enumeration emarks; String str; int nm; // Checks wheather the hashtable is empty System.out.println("Is Hashtable empty " + marks.isEmpty()); marks.put("Ankit", 58); marks.put("Amit", 88); marks.put("Shewta", 69); marks.put("Kriti", 99); marks.put("Joyti", 54); System.out.println("Is Hashtable empty " + marks.isEmpty()); // Creates enumeration of keys names = marks.keys(); while(names.hasMoreElements()) { str = (String) names.nextElement(); System.out.println(str + ": " + marks.get(str)); } /* nm = (Integer) marks.get("Janki"); marks.put("Janki", nm+15); System.out.println("Janki's new marks: " + marks.get("Janki")); // Creates enumeration of values
INTERNET TECHNOLOGY (CORE JAVA)
emarks = marks.elements(); while(emarks.hasMoreElements()) { nm = (Integer) emarks.nextElement(); System.out.println(nm); } // Number of entries in a hashtable System.out.println("The number of entries in a table are " + marks.size()); // Checking wheather the element available System.out.println("The element is their " + marks.containsValue(88)); */ // Removing an element from hashtable System.out.println("========"); marks.remove("Bharat"); names = marks.keys(); while(names.hasMoreElements()) { str = (String) names.nextElement(); System.out.println(str + ": " + marks.get(str)); } // Returning an String equivalent of the Hashtable System.out.println("String " + marks.toString()); // Emptying hashtable marks.clear(); System.out.println("Is Hashtable empty " + marks.isEmpty()); } }
Output : C:\java> javac Hash1.java C:\java> java Hash1 Amit: 88 Jyoti: 54 Ankit: 58 String {Kriti=99, Amit=88, Jyoti=54, Ankit=58} Is Hashtable empty true
WRAPPER CLASS IN JAVA Wrapper Class:
Java uses primitive types, such as int, char, double to hold the basic data types supported by the language. Sometimes it is required to create an object representation of these primitive types. These are collection classes that deal only with such objects. One needs to wrap the primitive type in a class. To satisfy this need, java provides classes that correspond to each of the primitive types. Basically, these classes encapsulate, or wrap, the primitive types within a class. Thus, they are commonly referred to as type wrapper. Type wrappers are classes that encapsulate a primitive type within an object. The wrapper types are Byte, Short, Integer, Long, Character, Boolean, Double, Float.
INTERNET TECHNOLOGY (CORE JAVA)
These classes offer a wide array of methods that allow to fully integrate the primitive types into Java‘s object hierarchy. Wrapper classes for converting simple types Converting primitive numbers to Object numbers using constructor methods NOTE : I, f, d and l are primitive data values denoting int, float, double and long data types. They may be constants or variables. Converting Object numbers to Primitive numbers using typeValue() method Converting Numbers to Strings using toString() method Converting String Object in to Numeric Object using static method ValueOf() Converting Numeric Strings to Primitive numbers using Parsing method NOTE : parseInt() and parseLong() methods throw a NumberFormatException if the value of the str does not represent an integer.
Byte class example in java: The Byte class encapsulates a byte value. It defines the constants MAX_VALUE and MIN_VALUE and provides these constructors: Byte(byte b) Byte(String str) Here, b is a byte value and str is the string equivalent of a byte value.
Prog. No.:- 68 import java.util.*; public class Byte_Test { public static void main(String args[]) { Byte_Test b1 = new Byte_Test ((byte)120); for(int i = 125; i<=135; i++) { Byte b2 = new Byte((byte)i); System.out.println("b2 = " + b2); } System.out.println("b1 Object = " + b1); System.out.println("Minimum Value of Byte = " + Byte.MIN_VALUE); System.out.println("Maximum Value of Byte = " + Byte.MAX_VALUE); System.out.println("b1* 2 = " + b1*2); System.out.println("b1* 2 = " + b1.byteValue()*2); Byte b3 = new Byte("120"); System.out.println("b3 Object = " + b3); System.out.println("(b1==b3)? " + b1.equals(b3)); System.out.println("(b1.compareTo(b3)? " + b1.compareTo(b3)); /*Returns 0 if equal. Returns -1 if b1 is less than b3 and 1 if b1 is
INTERNET TECHNOLOGY (CORE JAVA)
greater than 1*/ } }
Output : C:\java> javac Byte_Test.java C:\java> java Byte_Test b2 = 125 b2 = 126 b2 = 127 b2 = -128 b2 = -127 b2 = -126 b2 = -125 b2 = -124 b2 = -123 b2 = -122 b2 = -121 b1 Object = 120 Minimum Value of Byte = -128 Maximum Value of Byte = 127 b1* 2 = 240 b1* 2 = 240 b3 Object = 120 (b1==b3)? true (b1.compareTo(b3)? 0
Short : The Short class encapsulates a short value. It defines the constants MAX_VALUE and MIN_VALUE and provides the following constructors: Short(short s) Short(String str)
Prog. No.:- 69 import java.util.*; public class Short_Test { public static void main(String args[]) { Short_Test s1 = new Short_Test ((short)2345); for(int i = 32765; i<=32775; i++) { Short_Test s2 = new Short_Test ((short)i); System.out.println("s2 = " + s2); } System.out.println("s1 Object = " + s1); System.out.println("Minimum Value of Short = " + Short.MIN_VALUE); System.out.println("Maximum Value of Short = " + Short.MAX_VALUE); System.out.println("s1* 2 = " + s1.shortValue()*2); Short s3 = new Short("2345"); System.out.println("s3 Object = " + s3); System.out.println("(s1==s3)? " + s1.equals(s3)); Short s4 = Short.valueOf("10", 16); System.out.println("s4 Object = " + s4); }
INTERNET TECHNOLOGY (CORE JAVA)
}
Output : C:\java> javac Short_Test.java C:\java> java Short_Test s2 = 32765 s2 = 32766 s2 = 32767 s2 = -32768 s2 = -32767 s2 = -32766 s2 = -32765 s2 = -32764 s2 = -32763 s2 = -32762 s2 = -32761 s1 Object = 2345 Minimum Value of Short = -32768 Maximum Value of Short = 32767 s1* 2 = 4690 s3 Object = 2345 (s1==s3)? true s4 Object = 16
Integer class: The Integer class encapsulates an integer value. This class provides following constructors: Integer(int i) Integer(String str) Here, i is a simple int value and str is a String object.
Prog. No.:- 70 import java.util.*; public class Integer_Test { public static void main(String args[]) { Integer_Test i1 = new Integer_Test (12); System.out.println("I1 = " + i1); System.out.println("Binary Equivalent = " + Integer.toBinaryString(i1)); System.out.println("Hexadecimal Equivalent = " + Integer.toHexString(i1)); System.out.println("Minimum Value of Integer = " + Integer.MIN_VALUE); System.out.println("Maximum Value of Integer = " + Integer.MAX_VALUE); System.out.println("Byte Value of Integer = " + i1.byteValue()); System.out.println("Double Value of Integer = " + i1.doubleValue()); Integer_Test i2 = new Integer_Test (12); System.out.println("i1==i2 " + i1.equals(i2)); System.out.println("i1.compareTo(i2) = " + i2.compareTo(i1)); // Compareto - if it is less than it returns -1 else 1, if equal it return 0. Integer_Test i3 = Integer.valueOf("11", 16); System.out.println("i3 = " + i3); } }
INTERNET TECHNOLOGY (CORE JAVA)
Output : C:\java> javac Integer_Test.java C:\java> java Integer_Test I1 = 12 Binary Equivalent = 1100 Hexadecimal Equivalent = c Minimum Value of Integer = -2147483648 Maximum Value of Integer = 2147483647 Byte Value of Integer = 12 Double Value of Integer = 12.0 i1==i2 true i1.compareTo(i2) = 0 i3 = 17
Long : The Long class encapsulates a long value. It defines the constants MAX_VALUE and MIN_VALUE and provides the following constructors: Long(long l) Long(String str)
Prog. No.:- 71 import java.util.*; public class Long_Test { public static void main(String args[]) { Long_Test L1 = new Long_Test (68764); Long_Test L2 = new Long_Test ("686748"); System.out.println("Object L1 = " + L1); System.out.println("Object L2 = " + L2); System.out.println("Minimum Value of Long = " + Long.MIN_VALUE); System.out.println("Maximum Value of Long = " + Long.MAX_VALUE); System.out.println("L1 * 2 = " + L1 * 2); System.out.println("L1.longValue() * 2 = " + L1.longValue() * 2); System.out.println("L1.compareTo(l2) = " + L1.compareTo(L2)); System.out.println("L1==L2 ? = " + L1.equals(L2)); Long_Test L3 = Long.valueOf("10", 16); System.out.println("Object L3 = " + L3); System.out.println("Byte value of Long = " + L1.byteValue()); System.out.println("int value of Long = " + L1.intValue()); System.out.println("Double value of Long = " + L1.doubleValue()); int i = 12; System.out.println("Binary equivalent of decimal " + i + "=" + Long.toBinaryString(i)); System.out.println("Hexadecimal equivalent of decimal " + i + "=" + Long.toHexString(i)); } }
Output : C:\java> javac Long_Test.java C:\java> java Long_Test Object L1 = 68764
INTERNET TECHNOLOGY (CORE JAVA)
Object L2 = 686748 Minimum Value of Long = -9223372036854775808 Maximum Value of Long = 9223372036854775807 L1 * 2 = 137528 L1.longValue() * 2 = 137528 L1.compareTo(l2) = -1 L1==L2 ? = false Object L3 = 16 Byte value of Long = -100 int value of Long = 68764 Double value of Long = 68764.0 Binary equivalent of decimal 12=1100 Hexadecimal equivalent of decimal 12=c
Double class: The Double class encapsulates a double value. It defines several constants. The largest and smallest values are saved in MAX_VALUE and MIN_VALUE. The constant NaN (Not a Number) indicates that a value is not a number. If you divide a double number by zero, the result is NaN. This class defines these constructors: Double(double d) Double(String str) Here, d is a double value to be encapsulated in a Double object. In the last form, str is the string representation of a double value.
Prog. No.:- 72 import java.util.*; class Double_Test { public static void main(String args[]) { Double_Test d1 = new Double_Test (687642365.4563); Double_Test d2 = new Double_Test ("686748"); System.out.println("Object d1 = " + d1); System.out.println("Object d2 = " + d2); System.out.println("Minimum Value of Double = " + Double.MIN_VALUE); System.out.println("Maximum Value of Double = " + Double.MAX_VALUE); System.out.println("Byte value of Double = " + d1.byteValue()); System.out.println("int value of Double = " + d1.intValue()); System.out.println("Float value of Double = " + d1.floatValue()); Double_Test d3 = Double.parseDouble("765.89"); System.out.println("Double value from the string \"765.89\"="+d3); } }
Output : C:\java> javac Double_Test.java C:\java> java Double_Test Object d1 = 6.876423654563E8 Object d2 = 686748.0 Minimum Value of Double = 4.9E-324 Maximum Value of Double = 1.7976931348623157E308 Byte value of Double = -3
INTERNET TECHNOLOGY (CORE JAVA)
int value of Double = 687642365 Float value of Double = 6.8764237E8 Double value from the string "765.89"=765.89
Float class: The float class encapsulates a float value. It defines several constants the largest and smallest values are stored in MAX_VALUE and MIN_VALUE. The constant NaN indicates that a value is not a number. If you divide a floating – point number by zero, the result is NaN. This class defines these constructors: Float(float f) Float(double d) Float(String str) Here, f and d are float and double types to be encapsulated in a Float object. str is the string representation of a float value.
Prog. No.:- 73 import java.util.*; public class Float_Test { public static void main(String args[]) { Float_Test f1 = new Float_Test (123.5626); Float_Test f2 = new Float_Test (854.32f); Float_Test i = new Float_Test (10); System.out.println("Object f1 = " + f1); System.out.println("Object f2 = " + f2); System.out.println("Minimum Value of Float = " + Float.MIN_VALUE); System.out.println("Maximum Value of Float = " + Float.MAX_VALUE); System.out.println("Byte value of Float = " + f1.byteValue()); System.out.println("Short value of Float = " + f1.shortValue()); System.out.println("Integer value of Float = " + f1.intValue()); System.out.println("Double value of Float = " + f1.doubleValue()); System.out.println("(f1==f2) ?= " + f1.equals(f2)); System.out.println("f1.compareTo(f2) = " + f1.compareTo(f2)); System.out.println("f1 is not a number = " + i.isNaN()); } }
Output : C:\java> javac Float_Test.java C:\java> java Float_Test Object f1 = 123.5626 Object f2 = 854.32 Minimum Value of Float = 1.4E-45 Maximum Value of Float = 3.4028235E38 Byte value of Float = 123 Short value of Float = 123 Integer value of Float = 123 Double value of Float = 123.5625991821289 (f1==f2) ?= false f1.compareTo(f2) = -1 f1 is not a number = false
INTERNET TECHNOLOGY (CORE JAVA)
Character class: The Character class encapsulates a char value. This class provides the following constructor. Character(char ch) Here, c is a char value. charValue() method returns the char value that is encapsulated by a Character object and has the following form: char charValue().
Prog. No.:- 74 import java.util.*; public class Char_Test { public static void main(String args[]) { Character_Test c1 = new Character_Test ('m'); char c2 = 'O'; System.out.println("Object C1 = " + c1); System.out.println("char value of Character Object = " + c1.charValue()); System.out.println(c2 + " is defined character set ? " + Character.isDefined(c2)); System.out.println("c2 is digit = " + Character.isDigit(c2)); System.out.println("c2 is lowercase character = " + Character.isLowerCase(c2)); System.out.println("c2 is uppercase character = " + Character.isUpperCase(c2));
} }
Output : C:\java> javac Char_Test.java C:\java> java Char_Test Object C1 = m char value of Character Object = m O is defined character set ? true c2 is digit = false c2 is lowercase character = false c2 is uppercase character = true
Boolean class: The Boolean class encapsulates a Boolean value. It defines FALSE and TRUE constants. This class provides following constructors: Boolean(Boolean b) Boolean(String str) Here, b is a Boolean value and str is the string equivalent of a Boolean value. The methods associated with Boolean Class are as follows: 1. Boolean booleanValue() 2. Boolean equals(Boolean b) 3. String toString(Boolean b)
INTERNET TECHNOLOGY (CORE JAVA)
Prog. No.:- 75 import java.util.*; public class Boolean_Test { public static void main(String args[]) { Boolean_Test b1 = new Boolean_Test (true); Boolean_Test b2 = new Boolean_Test (false); System.out.println("Object B1 = " + b1); System.out.println("Object B2 = " + b2); Boolean_Test b3 = new Boolean_Test ("true"); Boolean_Test b4 = new Boolean_Test ("false"); System.out.println("Object B3 = " + b3); System.out.println("Object B4 = " + b4); System.out.println("Boolean Value = " + b1.booleanValue()); System.out.println("(b1==b2)? " + b1.equals(b2)); String S1 = b1.toString(); System.out.println("String S1 " + S1); } }
Output : C:\java> javac Boolean_Test.java C:\java> java Boolean_Test Object B1 = true Object B2 = false Object B3 = true Object B4 = false Boolean Value = true (b1==b2)? false String S1 true
STRING &STRING BUFFER IN JAVA String Handling:In Java, a string is defined as a sequence of characters. But, unlike many other languages that implement strings as character arrays, java implements strings as objects of type String. Java handles String by two classes StringBuffer and String. The String and StringBuffer classes are defined in java.lang. Thus, they are available to all programs automatically.
String Concatenation (+) Prog. No.:- 76 import java.util.*; class STest {
INTERNET TECHNOLOGY (CORE JAVA)
public static void main(String args[]) { STest s1 = new STest ("Java"); STest s2 = "2all"; STest s3 = s1+s2; System.out.println("S1 = " + s1); System.out.println("S2 = " + s2); System.out.println("Concatenation Operator = " + s1+s2); System.out.println("S3 = " + s3); byte num [] = {65,66,67,68}; STest s4 = new STest (num); System.out.println("S4 = " + s4); } }
Output : C:\java> javac STest.java C:\java> java STest S1 = Java S2 = 2all Concatenation Operator = Java2all S3 = Java2all S4 = ABCD
Character Extraction : The String class provides ways in which characters can be extracted from a String object.
String Comparison : The String class provides several methods that compare strings or substrings within strings. equals( ) – used to compare two strings General form: Boolean equals(Object str) Here, str is a String object. It returns true if the strings contain the same character otherwise it returns false. The comparison is case-sensitive. equalsIgnoreCase( ) – Same as equals but this ignores case. General form: Boolean equalsIgnoreCase(String str) Here, str is the String object. It returns true if the strings contain the same character otherwise it returns false. This is case in – sensitive. regionMatches( ) This method compares a specific region inside a string with another specific region in another string. There is an overloaded form that allows you to ignore case in such comparisons. General form: Boolean regionMatches(int startIndex, String str2, int str2StartIndes, int numChars) Boolean regionMatches(Boolean ignoreCase, int startIndex, String str2, int str2StartIndex, int numChars) startsWith( ) and endsWith() The startsWith( ) method determines whether a given String begins with a specified string. endsWith( ) determines whether the String ends with a specified string. General Form
INTERNET TECHNOLOGY (CORE JAVA)
Boolean startsWith(String str) Boolean endsWith(String str) equals( ) Versus = = Equals( ) method and the = = operator perform two different operations. The equals ( ) method compares the characters inside a String object. The = = operator compares two object references to see whether they refer to the same instance. compareTo( ) It is not enough to know that two strings just for equal or not. For sorting applications, we need to know which is less than, equal to, or greater than the other string. The String method compareTo( ) serves this purpose. General Form: int compareTo(String str) Modifying a string : If we want to modify a String, we must either copy it into a StringBufer or we can use following String methods:
valueOf() : The valueOf() method converts data from internal format into a human-readable form. It has several forms: String valueOf(double num) String valueOf(long num) String valueOf(Object ob) String valueOf(char chars[ ] ) String valueOf(char chars[], int startIndex, int numChars)
String Buffer class: StringBuffer is a peer class of String. String creates strings of fixed length, while StringBuffer creates strings of flexible length that can be modified in terms of both length and content. So Strings that need modification are handled by StringBuffer class. We can insert characters and substrings in the middle of a string, or append another string to the end. StringBufer defines these Constructors: StringBuffer() StringBuffer(int size) StringBuffer(String str)
Method Call Sb.length() Sb.capacity() setLength(int len) charAt(int where)
Task Performed Gives the current length of a StringBuffer. Gives the total allocated capacity (default 16) Set the length of the buffer within a String Buffer object. Gives the value of character
INTERNET TECHNOLOGY (CORE JAVA)
setCharAt(int where, char ch) S1.append(s2) S1.insert(n,s2) S1.reverse() S1.deleteCharAt(nth) S1.delete(StartIndex, endIndex)
Set the value of a character within a StringBuffer. Appends the string s2 to s1 at the end Inserts the string s2 at the position n of the string s1 Reverse the string of s1 Delete the nth character of string s1 Delete characters from start to end.
Prog. No.:- 77 import java.util.*; class Strbuf_Test { public static void main(String args[]) { Strbuf_Test s1 = new Strbuf_Test (); Strbuf_Test s2 = new Strbuf_Test ("Anurag"); Strbuf_Test s3 = new Strbuf_Test (s2); Strbuf_Test s4 = new Strbuf_Test (100); System.out.println("s1 = " + s1); System.out.println("s2 = " + s2); System.out.println("s3 = " + s3); System.out.println("s1.length System.out.println("s2.length System.out.println("s3.length System.out.println("s4.length
= = = =
" " " "
+ + + +
s1.length()); s2.length()); s3.length()); s4.length());
System.out.println("s1.capacity System.out.println("s2.capacity System.out.println("s3.capacity System.out.println("s4.capacity
= = = =
" " " "
+ + + +
s1.capacity()); s2.capacity()); s3.capacity()); s4.capacity());
} }
Output : C:\java> javac Strbuf_Test.java C:\java> java Strbuf_Test s1 = s2 = Anurag s3 = Anurag s1.length = 0 s2.length = 9 s3.length = 9 s4.length = 0 s1.capacity = 16 s2.capacity = 25 s3.capacity = 25 s4.capacity = 100
Prog. No.:- 78 INTERNET TECHNOLOGY (CORE JAVA)
import java.util.*; class Strbuf2_Test { public static void main(String args[]) { Strbuf2_Test s1 = new Strbuf2_Test ("Anurag Rana"); Strbuf2_Test s2 = new Strbuf2_Test ("Hello"); System.out.println("s1 = " + s1); //System.out.println("s1.charAt(6) = " + s1.charAt(6)); //s1.setCharAt(6,'z'); //System.out.println("s1 = " + s1); //System.out.println("Inserting String = " + s1.insert(6,s2)); //System.out.println("s1 = " + s1); //System.out.println("Appending String = " + s1.append(s2)); //System.out.println("s1 = " + s1); //System.out.println("Reversing String = " + s1.reverse()); //System.out.println("Deleting 6th character = " + s1.deleteCharAt(6)); System.out.println("Deleting 6 to 11 character = " + s1.delete(6,11)); } }
Output : C:\java> javac Strbuf2_Test.java C:\java> java Strbuf2_Test s1 = Anurag Rana Deleting 6 to 11 character = Anurag
Prog. No.:- 79 import java.util.*; public class Strbuf3_Test { public static void main(String[] args) { Strbuf3_Test s = new Strbuf3_Test ("Hello world!"); System.out.println("s = " + s); System.out.println("s.length() = " + s.length()); System.out.println("s.length() = " + s.capacity()); // Change the length of buffer to 5 characters: s.setLength(5); System.out.println(s); System.out.println("s.length() = " + s.length()); System.out.println("s.length() = " + s.capacity()); } }
Output : C:\java> javac Strbuf3_Test.java C:\java> java Strbuf3_Test s = Hello world! s.length() = 12 s.length() = 28
INTERNET TECHNOLOGY (CORE JAVA)
Hello s.length() = 5 s.length() = 28
EXCEPTION HANDLING IN JAVA Exception handling: Exception is a run-time error which arises during the execution of java program. The term exception in java stands for an “exceptional event”. So Exceptions are nothing but some abnormal and typically an event or conditions that arise during the execution which may interrupt the normal flow of program. An exception can occur for many different reasons, including the following: · A user has entered invalid data. · A file that needs to be opened cannot be found. · A network connection has been lost in the middle of communications, or the JVM has run out of memory. ―If the exception object is not handled properly, the interpreter will display the error and will terminate the program. Now if we want to continue the program with the remaining code, then we should write the part of the program which generate the error in the try{} block and catch the errors using catch() block.. Exception turns the direction of normal flow of the program control and send to the related catch() block and should display error message for taking proper action. This process is known as Exception handling.‖ The purpose of exception handling is to detect and report an exception so that proper action can be taken and prevent the program which is automatically terminate or stop the execution because of that exception. Java exception handling is managed by using five keywords: try, catch, throw, throws and finally. Try: Piece of code of your program that you want to monitor for exceptions are contained within a try block. If an exception occurs within the try block, it is thrown. Catch: Catch block can catch this exception and handle it in some logical manner. Throw: System-generated exceptions are automatically thrown by the Java run-time system. Now if we want to manually throw an exception, we have to use the throw keyword. Throws: If a method is capable of causing an exception that it does not handle, it must specify this behavior so that callers of the method can guard themselves against that exception. You do this by including a throws clause in the method‘s declaration. Basically it is used for IOException. A throws clause lists the types of exceptions that a method might throw. This is necessary for all exceptions, except those of type Error or RuntimeException, or any of their subclasses. All other exceptions that a method can throw must be declared in the throws clause. If they are not, a compile-time error will result. Finally: Any code that absolutely must be executed before a method returns, is put in a finally block. General form: try { // block of code to monitor for errors
INTERNET TECHNOLOGY (CORE JAVA)
} catch (ExceptionType1 e1) { // exception handler for ExceptionType1 } catch (ExceptionType2 e2) { // exception handler for ExceptionType2 } // ... finally { // block of code to be executed before try block ends } Exception Hierarchy: All exception classes are subtypes of the java.lang.Exception class. The exception class is a subclass of the Throwable class. Other than the exception class there is another subclass called Error which is derived from the Throwable class. Errors : These are not normally trapped form the Java programs. Errors are typically ignored in your code because you can rarely do anything about an error. These conditions normally happen in case of severe failures, which are not handled by the java programs. Errors are generated to indicate errors generated by the runtime environment. For Example : (1) JVM is out of Memory. Normally programs cannot recover from errors. (2) If a stack overflow occurs then an error will arise. They are also ignored at the time of compilation. The Exception class has two main subclasses: (1) IOException or Checked Exceptions class and (2) RuntimeException or Unchecked Exception class (1) IOException or Checked Exceptions : Exceptions that must be included in a method‘s throws list if that method can generate one of these exceptions and does not handle it itself. These are called checked exceptions. For example, if a file is to be opened, but the file cannot be found, an exception occurs. These exceptions cannot simply be ignored at the time of compilation. Java’s Checked Exceptions Defined in java.lang (2) RuntimeException or Unchecked Exception : Exceptions need not be included in any method‘s throws list. These are called unchecked exceptions because the compiler does not check to see if a method handles or throws these exceptions. As opposed to checked exceptions, runtime exceptions are ignored at the time of compilation. Java’s Unchecked RuntimeException Subclasses.
Try and catch in java: Prog. No.:- 80 public class TC_Test {
INTERNET TECHNOLOGY (CORE JAVA)
public static void main(String[] args) { int a=10; int b=5,c=5; int x,y; try { x = a / (b-c); } catch(ArithmeticException e) { System.out.println("Divide by zero"); } y = a / (b+c); System.out.println("y = " + y); } }
Output : C:\java> javac TC_Test.java C:\java> java TC_Test Divide by zero y = 1
Note that program did not stop at the point of exceptional condition.It catches the error condition, prints the error message, and continues the execution, as if nothing has happened. If we run same program without try catch block we will not gate the y value in output. It displays the following message and stops without executing further statements. Exception in thread "main" java.lang.ArithmeticException: / by zero at Thrw_Excp.TC_Demo.main(TC_Demo.java:10) Here we write ArithmaticException in catch block because it caused by math errors such as divide by zero. Now how to display description of an exception ? The description of thrown object by using it in a println() statement by simply passing the exception as an argument. For example; catch (ArithmeticException e) { system.out.pritnln(―Exception:‖ +e); } Multiple catch blocks : ?It is possible to have multiple catch blocks in our program.
Prog. No.:- 81 public class MultiCatch
INTERNET TECHNOLOGY (CORE JAVA)
{ public static void main(String[] args) { int a [] = {5,10}; int b=5; try { int x = a[2] / b - a[1]; } catch(ArithmeticException e) { System.out.println("Divide by zero"); } catch(ArrayIndexOutOfBoundsException e) { System.out.println("Array index error"); } catch(ArrayStoreException e) { System.out.println("Wrong data type"); } int y = a[1]/a[0]; System.out.println("y = " + y); } }
Output : C:\java> javac MultiCatch.java C:\java> java MultiCatch Array index error y = 2
Note that array element a[2] does not exist. Therefore the index 2 is outside the array boundary. When exception in try block is generated, the java treats the multiple catch statements like cases in switch statement. The first statement whose parameter matches with the exception object will be executed, and the remaining statements will be skipped. When you are using multiple catch blocks, it is important to remember that exception subclasses must come before any of their superclasses. This is because a catch statement that uses a superclass will catch exceptions of that type plus any of its subclasses. Thus, a subclass will never be reached if it comes after its superclass. And it will result into syntax error. // Catching super exception before sub
Prog. No.:- 82 class etion3 { public static void main(String args[]) { int num1 = 100; int num2 = 50; int num3 = 50; int result1; try { result1 = num1/(num2-num3); System.out.println("Result1 = " + result1); } catch (Exception e)
INTERNET TECHNOLOGY (CORE JAVA)
{ System.out.println("This is mistake. "); } catch(ArithmeticException g) { System.out.println("Division by zero"); } } }
Output : If you try to compile this program, you will receive an error message because the exception has already been caught in first catch block. Since ArithmeticException is a subclass of Exception, the first catch block will handle all exception based errors, including ArithmeticException. This means that the second catch statement will never execute. To fix the problem, revere the order of the catch statement. Nested try statements: The try statement can be nested. That is, a try statement can be inside a block of another try. Each time a try statement is entered, its corresponding catch block has to enter. The catch statements are operated from corresponding statement blocks defined by try.
Prog. No.:- 83 public class NestedTry { public static void main(String args[]) { int num1 = 100; int num2 = 50; int num3 = 50; int result1; try { result1 = num1/(num2-num3); System.out.println("Result1 = " + result1); try { result1 = num1/(num2-num3); System.out.println("Result1 = " + result1); } catch(ArithmeticException e) { System.out.println("This is inner catch"); } } catch(ArithmeticException g) { System.out.println("This is outer catch"); } } }
Output : C:\java> javac NestedTry.java C:\java> java NestedTry This is outer catch.
Finally:
INTERNET TECHNOLOGY (CORE JAVA)
Java supports another statement known as finally statement that can be used to handle an exception that is not caught by any of the previous catch statements. We can put finally block after the try block or after the last catch block. The finally block is executed in all circumstances. Even if a try block completes without problems, the finally block executes.
Prog. No.:- 84 public class Finally_Test { public static void main(String args[]) { int num1 = 100; int num2 = 50; int num3 = 50; int result1; try { result1 = num1/(num2-num3); System.out.println("Result1 = " + result1); } catch(ArithmeticException g) { System.out.println("Division by zero"); } finally { System.out.println("This is final"); } } }
Output : C:\java> javac Finally_Test.java C:\java> java Finally_Test Division by zero This is final
Throw: We saw that an exception was generated by the JVM when certain run-time problems occurred. It is also possible for our program to explicitly generate an exception. This can be done with a throw statement. Throw object; Inside a catch block, you can throw the same exception object that was provided as an argument. Syntax: catch(ExceptionType object) {
INTERNET TECHNOLOGY (CORE JAVA)
throw object; } Alternatively, you may create and throw a new exception object as follows: Throw new ExceptionType(args); Here, exceptionType is the type of the exception object and args is the optional argument list for its constructor. When a throw statement is encountered, a search for a matching catch block begins and if found it is executed.
Prog. No.:- 85 class Throw_Test { public static void a() { try { System.out.println("Before b"); b(); } catch(ArrayIndexOutOfBoundsException j) //manually thrown object catched here { System.out.println("J : " + j) ; } } public static void b() { int a=5,b=0; try { System.out.println("We r in b"); System.out.println("********"); int x = a/b; } catch(ArithmeticException e) { System.out.println("c : " + e); throw new ArrayIndexOutOfBoundsException("demo"); } } public static void main(String args[]) { try { System.out.println("Before a"); a(); System.out.println("********"); System.out.println("After a"); } catch(ArithmeticException e) { System.out.println("Main Program : " + e);
INTERNET TECHNOLOGY (CORE JAVA)
//throw from here
} } }
Output : C:\java> javac Throw_Test.java C:\java> java Throw_Test Before a Before b We r in b ******** c : java.lang.ArithmeticException: / by zero J : java.lang.ArrayIndexOutOfBoundsException: demo ******** After a
Throwing our own object : ?If we want to throw our own exception, we can do this by using the keyword throw as follow. throw new Throwable_subclass; Example : throw new ArithmaticException( ); throw new NumberFormatException( );
Prog. No.:- 86 import java.lang.Exception; class MyException extends Exception { MyException(String message) { super(message); } } class TestMyException { public static void main(String[] args) { int x = 5, y = 1000; try { float z = (float)x / (float)y; if(z < 0.01) { throw new MyException("Number is too small"); } } catch(MyException e) { System.out.println("Caught MyException"); System.out.println(e.getMessage()); } finally { System.out.println("uiit.hpu");
INTERNET TECHNOLOGY (CORE JAVA)
} } }
Output : C:\java> javac TestMyException.java C:\java> java TestMyException Caught MyException Number is too small uiit.hpu
Here The object e which contains the error message "Number is too small" is caught by the catch block which then displays the message using getMessage( ) method. NOTE: Exception is a subclass of Throwable and therefore MyException is a subclass of Throwable class. An object of a class that extends Throwable can be thrown and caught.
Throws: If a method is capable of causing an exception that it does not handle, it must specify this behavior so that callers of the method can guard themselves against that exception. We do this by including a throws clause in the method‘s declaration. Basically it is used for IOException. A throws clause lists the types of exceptions that a method might throw. This is necessary for all exceptions, except those of type Error or RuntimeException,or any of their subclasses. All other exceptions that a method can throw must be declared in the throws clause. If they are not, a compile-time error will result. General form of a method declaration that includes a throws clause: type method-name(parameter-list) throws exception-list { // body of method } Here, exception-list is a comma-separated list of the exceptions that a method can throw. Throw is used to actually throw the exception, whereas throws is declarative statement for the method. They are not interchangeable.
Prog. No.:- 87 class NewException extends Exception { public String toS() { return "You are in NewException "; } } class Customexception { public static void main(String args[]) { try { doWork(3); doWork(2); doWork(1);
INTERNET TECHNOLOGY (CORE JAVA)
doWork(0); } catch (NewException e) { System.out.println("Exception : " + e.toS()); } } static void doWork(int value) throws NewException { if (value == 0) { throw new NewException(); } else { System.out.println("****No Problem.****"); } } }
Output: C:\java> javac Customexception.java C:\java> java Customexception ****No Problem.**** ****No Problem.**** ****No Problem.****
MULTITHREADING IN JAVA Thread: A thread is a single flow of control like simple program. A unique property of java is multithreading only because java supports multithreading. More than one thread (program) run simultaneously is known as multithreading (multiprogramming). In multithreading java interpreter handles the switching of control between the threads in such a way that it looks like they are running concurrently. Multithreading is useful in a number of ways. We can divide a long program into number of threads and executes them in parallel.
The Main Thread: When our simple program starts one single thread begins running immediately. This is called our single main thread. The main thread create automatically when program is started.
It is very important thread because of two reasons: 1.) From the main thread other child thread will be created. 2.) Main thread is all most everytime stop running lastly because it has to remove or shutdown few resources as well as few action.
Now the question is how can we control our main thread? Actually by calling the method currentThread() of Thread class we can control our main thread.
INTERNET TECHNOLOGY (CORE JAVA)
Prog. No.:- 88 (Main Thread.) public class Main_Thread { public static void main(String args[]) { Main_Thread t = Main_Thread.currentThread(); System.out.println("Current thread: " + t); // change the name of the thread t.setName("My Thread"); System.out.println("After name change: " + t); try { for(int n = 5; n > 0; n--) { System.out.println(n); //print number with interval of 1 sec. Thread.sleep(1000); //Thread is going to sleep for 1 sec. } } catch (InterruptedException e) { System.out.println("Main thread interrupted"); } } }
Output: C:\java> javac Main_Thread.java C:\java> java Main_Thread Current thread: Thread[main,5,main] After name change: Thread[My Thread,5,main] 5 4 3 2 1
Here first of all we give reference of our current main single thread to t by thread object and currentThread() method. The number 5 to 1 will be print at interval of 1 second due to sleep method. Thread will go to sleep for 1000 ms. due to sleep method
Thread Life Cycle: Thread has many different state through out its life. 1 Newborn State 2 Runnable State 3 Running State 4 Blocked State 5 Dead State
INTERNET TECHNOLOGY (CORE JAVA)
1 Newborn State: When we create a thread it will be in Newborn State. The thread is just created still its not running. We can move it to running mode by invoking the start() method and it can be killed by using stop() method.
INTERNET TECHNOLOGY (CORE JAVA)
2 Runnable State: It means that thread is now ready for running and its waiting to give control. We can move control to another thread by yield() method.
3 Running State: It means thread is in its execution mode becaause the control of cpu is given to that particular thread. It can be move in three different situation from running mode.
INTERNET TECHNOLOGY (CORE JAVA)
4 Blocked State: A thread is called in Blocked State when it is not allowed to entering in Runnable State or Running State. It happens when thread is in waiting mode, suspended or in sleeping mode. 5 Dead State: When a thread is completed executing its run() method the life cycle of that particular thread is end. We can kill thread by invoking stop() method for that particular thread and send it to be in Dead State.
Create Thread: We can create thread in java with two different ways. 1. Extending the Thread Class. 2. Implements runnable interface. .
1. Extending the Thread class: INTERNET TECHNOLOGY (CORE JAVA)
In this method one normal class extends the inbuilt class thread and override its run() method with the code required by that particular thread. Here we are going to extend class java.lang.Thread. so we can access all the methods of thread class. Create one class which extends the thread class. Override the run method and put lines of code inside thread method that will be perform by thread. Create an object of class which we created with extending the thread class and call the start() method to execute the thread. Class MyThread extends Thread { ……………….. ……………….. } So now we have one thread named MyThread. Implementing the run() method Public void run() { ……… // Thread code here } Starting new Thread MyThread aTh = new MyThread(); // it instantiates a new object of class MyThread aTh.start(); // invokes run() method
Prog. No.:- 89(Extending the Thread class.) class A extends Thread { public void run() { System.out.println("Thread A"); for(int i=1;i<=5;i++) { System.out.println("From thread A i = " + i); } System.out.println("Exit from A"); } } class B extends Thread { public void run() { System.out.println("Thread B"); for(int i=1;i<=5;i++) { System.out.println("From thread B i = " + i); } System.out.println("Exit from B"); } } public class Thread_Class { public static void main(String[] args) { new A().start(); //creating A class thread object and calling run method
INTERNET TECHNOLOGY (CORE JAVA)
new B().start(); //creating B class thread object and calling run method System.out.println("End of main thread"); } }
Output : C:\java> javac Thread_Class.java C:\java> java Thread_Class Thread A From thread A i = 1 From thread A i = 2 From thread A i = 3 From thread A i = 4 From thread A i = 5 Exit from A End of main thread Thread B From thread B i = 1 From thread B i = 2 From thread B i = 3 From thread B i = 4 From thread B i = 5 Exit from B
2. Implementing the Runnable interface: In this method we have one interface named runnable and we implements this interface for implement a thread. Create one class which implements runnable interface. Override the run() method and put some line of code for that particular thread. Now create an object of inbuilt thread class and create an object of class that implements runnable interface. Give the reference of object to thread object by passing an argument (argument must be the object of class which implements the runnable interface) while creating a thread object. Call the start() method to run the thread.
Prog. No.:- 90 (Implementing the Runnable interface.) public class Thread_Interface { public static void main(String[] args) { X x1 = new X(); //class object Thread xthread = new Thread(x1); //creating thread object and giving reference of class object to thread object xthread.start(); System.out.println("End of main Thread"); } } class X implements Runnable { public void run() { System.out.println("Inside X thread"); for(int i=1;i<=10;i++) { System.out.println("From xthread i = " +i); } System.out.println("Exit from X"); } }
INTERNET TECHNOLOGY (CORE JAVA)
Output : C:\java> javac Thread_Interface.java C:\java> java Thread_Interface End of main Thread Inside X thread From xthread i = 1 From xthread i = 2 From xthread i = 3 From xthread i = 4 From xthread i = 5 From xthread i = 6 From xthread i = 7 From xthread i = 8 From xthread i = 9 From xthread i = 10 Exit from X
INTERNET TECHNOLOGY (CORE JAVA)