Java Unit 1 Khader Sir

You might also like

Download as pdf
Download as pdf
You are on page 1of 22
N. CH! Prepared By Khadar 9966648277 INTRODUCTION CREATION OF JAVA: Java was developed by a team of Sun Micro Systems which consisted of James Gosling, Patrick Naughton, Chris Warth, Ed Frank and Mike Sheridan, This language was initially called “Oak” but was renamed as Javain 1995, The Primary goal of the team was to develop a Platform Independent Language. Java is related to C++, which is a direct descendent of C. Much of the features of Java is inherited from these two languages. From C, Java derivesits syntax. Many of Java’s object oriented feature are influenced by C++. Because of the similarities between Java and C+, Java is usually treated as “Internet Version of C++”. But Java was not designed to replace C++. Java was designed to solve a certain set of problems and C++ was designed to solve a different set of problems. Both languages will exist without affecting each other. Java is mainly for Internet Programming and C, C++ are mainly for systems programming. JAVA APPLETS & APPLICATIONS: Java can be used to create two types of programs: Applications and Applets.An application is a program that runs under the control of the Operating System. An Applet is a Program designed to transmit over the Internet and is executed by a Java compatible Web Browser. SECURITY: The Active programs cause security problems to the Clients. When we use Java compatible web browser, we can safely download Java Applets without fear of viral Infections. Java achieves this protection by restricting a Java program to the Java execution environment and not allowing it to access other parts of the Computer. PORTABILITY: Many types of computers and operating systems are used on Internet. For programs to be dynamically downloaded to various types of platforms, the executable code must be Portable. Java is platform independent and is best suitable for this purpose. BYTE CODE: & Byte code is an optimized set of instructions to be executed by the Java runtime system i.e., Java Virtual Machine (JVM). JVM is an interpreter for byte code. Byte code is the output of the Java compiler. Translating a java program into byte code makes it much easier to run a program in a variety of environments. Scanned with CamScanner ~/ J Q Prepared By Khadar 996664877 & if 3 JAVA BUZZWORDS: = Although, the primary goal for invention of Java are portability and Security, other 7 factors also played an important role. The key features were summed up by the Java team in the following list of Buzzwords. |.Simple: Java is designed to be easy for the programmer to learn and use. For a programmer who understands the basic concepts of object oriented programming, learning java will be easier. lObject-Oriented: Java is a pure object oriented language. This makes it very useful in a wide variety of application development. MLROBUST: As java is platform independent language, the programs must execute reliably in a variety of systems. Thus, the ability to create robust programs was given a high priority in the design of java. The two main reasons for program failure are memory management mistakes and mishandled exceptions. Java eliminates this by providing automatic garbage collection and object oriented exception handling mechanism. \V.Multi-Threading: Java supports multi-threaded programming, which allows to write programs that do many things simultaneously. V.Interpreted: Java enables the creation of portable programs by compiling into an intermediate representation called byte code. This byte code can be interpreted on any system that provide a Java Virtual Machine. Eee : ~ Scanned with CamScanner Prepared By Khadar 9966648277 All object oriented programming languages provide mechanism that is used to implement the object oriented model. They are encapsulation, inheritance and polymorphism. Encapsulation: Encapsulation is the mechanism that binds together code and the data it operates on. It keeps the data safe from outside code and misuse . This principle is used to implement information hiding. In Java, the basics of encapsulation is “class”. Inheritance: Inheritance is the property by which a unit can be described from an existing unit. In java, the ability to write a class that inherits the member variables and methods of another class is called Inheritance. Inheritance decrease the coding part of programmer. Polymorphism: Polymorphism is a Greek word that means Many forms. It is a feature that allows one interface to be used for a set of actions that have almost same operation. It is the compiler's job to select the particular action depending on each situation. DATA-TYPES: The data type determines the types of the data that a variable can store. The type of a particular variable is specified by using a type name in the variable declaration. Java has eight fundamental or primitive data types. They are divided into four categories. Linteger Data Type:- These are four data types in this category. All of these are signed, that can store both negative and positive values. The four integer types differ in the range of values they can store, Description It occupies one byte and range is -128 to 127 It takes two bytes and range is-32768 to 32767 It takes four bytes and can have values from -2147483648 to 2147483647 Scanned with CamScanner ’ = v g a Prepared By Khadar 9966644, ¥ long —tr occupies’ bytes and have a range of & -9223372036854775808 to 9223372036854775807 4 ULFloating- point Data type: Numerical values that consists of a decimal point are stored as a floating point numbers, These are two basic floating points in JAVA. They are float and double. Data-Type Description float ———> It takes bytes and can have values from -3.4£38(-3.4X10")to +3.4£38(3.4x10"), double ————> It takes 8bytes and can have values from -1.7E308 to +1.7£308. lll.Character data type: Variable of types char is used to store a single character. It occupies two bytes in memory. Characters are designated by enclosing them in single quotes. |V.Boolean Data Type: ‘ Boolean data type is used to declare variable which can have only one of the two values; True to False. The Boolean data type differ from other primitive data type in that they cannot be cast to any other basic type and other basic types cannot be cast to Boolean. VARIABLE! A Variable is name given to memory location that is used to store information in a program. Each Variable can be used to store only one data type of values. Before using a variable, its type and name must be declared. Variable names must follow some rules: |. AVariable name can be of any length. I. Itcan contain alphabets, digits and underscore. Ill, It must start with an alphabets or an underscore.’ IV. It must not include blanks. V. It must not be a keyword. DECLARING VARIABLES: All the variables has to be declared before using. The general syntax to declare a variable is: data-type _variable-name; Scanned with CamScanner Prepared By Khadar 9966648277 The “data-type” specifies the type of the data a variable can store. poss Example: intaum; float salary; boolean x; ized when they are declared. The Variables can also be initi Example: _intnum=10; CONTROL STATEMENTS:- These are the statements which are used to control the flow of execution of a program. if-Statement: The “if” statement is used to execute a statement or a block of statements if the given condition is true. Its general form is: AX te(condition or expression) { statement statement’ Vs If-else statement The basic “if” statement can be extended by adding an “else” statement. This provides a second choice of statement to be executed if the condition is false. Its general formis : { H(condition or expression) { statement4;- Glukiment \ > else Statement x; Scanned with CamScanner wv Prepared By Khadar 9966, } Nested if statement: An if statement can again contain an if statement. Also the else part can also contain an if statement. This is called Nested If statements. This nesting can continue upto as many levels as needed, ‘Switch statement A switch statement is used to select from multiple choices based on a condition or expression. The expression must produce a result of type char ,byte, Otherwise the statement will not compile. Syater . The general form of a switch statement is : PF endibon) switch( expression) a ; ‘ iP Gendron) Short or int. case 1; S1 \ f break; Se ou; case 2: 3 se ese break; u See ; ; Stu, | default: . ae | e } SF Sey os; ! St 67 The expression in switch statement determines the Particular case tobe executed. The A loop is used to execute a statement or block of statements repeatedly. These are three loop statements. They are as follows: 1. For-loop: Its general form is for(initialization; condition; altering expression) { statements; Scanned with CamScanner Prepared By Khadar 9966648277 } A for loop has 3 parts separated by semicolons(;). The first part, Initialization, is executed before the execution of loop starts. This is used to initialize a counter for the number of loop iterations. execution of the loop statements continuous as long as the condition, in second part is true . This condition is checked at the beginning of each loop iteration. The altering expression is for increment or decrement the loop counter. This is executed at the end of each loop, iteration. 2. While -loop:Its general form is while(expression) { statements ; The loop executes as long as the given expression or condition evaluates to true. The expression is tested at the beginning of each iteration. 3. Do-while-loop: Its general form is dof statements ; Jwhile(expression or condition); It is similar to while loop, except that the expression is tested at the end of each iteration. Thus, the block of statements is executed atleast once, even if the expression is always false. ARRAYS: A . sorta ani y ae '8 a collection of simitar elements refer by single name. All the array elements are stored in consecutive memory locations. Every location has a index, by using that index we can access the particular element in the array .The first element will have an index 0, the second will have an index 1, the third an index 2&. Declaring an Array: Scanned with CamScanner ov Prepared By Khadr ang An array is declared using the following syntax. data-type [] array-name; (or) data-type array-name| J; is ing an array and not for The square brackets indicates that the array-name Is for referencing t declaration. storing a single value. NO memory is allocated to the array a Defining an Array: After declaring an array, it can be defined as follows: array-name=new data-type[size]; Here “size” is the number of elements the array contains. Example: primes=new int{10]; The declaration and definition can be combined in a single statement as follows: data-type array-name [ ]=new data-typelsize]; tox bE] = ne nia lengn) Accessing Array Elements: An element of an array is accessed by using the array-name followed by the index value enclosed in square brackets. The index need not be a variable or constant only. It can be an expression that evaluates to a positive integer of type int. Ifa value of type long is used as index then it gives an error. Example: —_ int x=a[5); ‘The above statement assigns the sixth elements of the array to the variable x. The maximum index value for an array is one less than the number of elements in the array. Java compiler checks whether the index value used is valid or not. If the index value is less than zero or greater than array’s size-1 then an exception called “ArraylndexOutOfBounds ” is thrown. Initializing Array: An array can be initialized with the values when it is declared, For Example: Scanned with CamScanner Prepared By Khadar 9966648277 int primes{]=(2,3,5,7,11,13}; he array is created with sufficient elements to store all the values that appear between the braces. The array size is determined by the number of initial values. Array Length: The length of an array can be known be using “length”. For example, for an array called “primes a data member of the “array “ object called ”, the length is given by primes.length. OPERATOR: The operators in java are divided into different categories as follows: |. Arithmetic Operators: The arithmetic operators are as follows: 1. + ———> ForAddition - ———> For Subtraction ———> for Division(Gives Quotient) ——> for Multiplication % + ———> For Modulo division(gives remainder) vPen All these operators are binary operators, that is they need a minimum of two operands to produce a result. All these operators can be applied to both integerand float data types. II. Comparison Operators: Comparison operators are used to create logical expressions which results in a value of true or false. The comparison operators that are available are: Equals to (Comparison) Less than Greater than Less than or equal to Greater than or equal to Not equal to oy ae ML, Logical Operators: Logical operators are used to combine two or more logical expressions into a more complex logical expression. 1. && = ——> Logical AND —Requires all the expressions to be true 21 —_— Logical OR -- Evaluates to true, if atleast one . expression is true 3. LogicatExctusive OR-used to determine if one and Scanned with CamScanner only one expression is true. 4. ! Logica NOT—Iaverts the value of a logical expression. \V.Bitwise Operators : m 4 Prepared By Khadar 3966, = § # ge FP ¢ All the integer values are represented internally in bits. Bitwise operators are used to Operate on bit values of integers. 1. | ———> _ Bitwise OR - Produces 1 if atleast one bit is 1 2. & ————> _Bitwise AND - Produces 1 if both bits in corresponding position are 1 3.8 ——> 4~ —— Number, V. Shift Operators: Bitwise Ex-or—Produces 1 if both bits are same. Bitwise Complement — Inverts all the bits of the These operators are used to shift the bits of an integers to the left or right. It is equal to multiplying or dividing by a power of two. 1.<< ——_» ‘shift left, fill zeros at right 2.>> ————> ‘Shift right, fill sign bit at left Vi.increment & Decrement Operators: These operators are used to increase or decrease the value of a variable by 1. These are of two types : Post — increment or post - decrement and pre- increment or pre- decrement. Example: int a: att; // makes a=6 a--; // makes a=5 Vil,Unary Operators: The unary + and unary ~ operators, takes only one argument (or operand). The unary ~ operator is used to change the sign of the operand. VIIL. Assignment Operator: This operator is used to assign values to a variable .The left side of this variable must be a variable .The right side of this operator can be a constant or an expression or some variable. Example : int x=5; int a=b+c; ‘ é gs og > € Pe = Ne, eC Scanned with CamScanner Prepared By Khadar 9966648277 pecial Operators: jere are some special operators like: new —used-toallocate memory instanceof > — toget the type or name of an object () —Funetian call operator Ul Subscript operator used with arrrays TYPECONVERSION & CASTING: itis a common to assign a value of one type to a variable of another type. If the two types are compatible then java performs automatic conversion between incompatible types, casting is used; which performs an explicit conversion. Explicit conversion To create conversion between incompatible types i.e., for explicit conversion casting is used, It has the general form as follows: (target-data-type) value Here target-data-type specifies that desired type to convert the specified value to. If the destination is smaller than the source then the value is truncated. COMPILING AND RUNNING A JAVA PROGRAM: A Java program can be compiled and run from command prompt. Compiling: The command for compiling a java program is javac Syntax: javacfilenamejava <1 Running: the command for running java program is java Syntax: java filename Class Fundamentals: onto A class is a user defined data type. it encapsulate the variables and function. A class is declared by the use of “class” keyword. The general form of a class is: classclass-name { Scanned with CamScanner Vv K Prepared By Khadar soe £ Data-type variablel, variable2, & 3 Return-type methodname-1 (parameter-list) & { ody of method } Return-type methodname~2 (parameter-list) ( //pody of method ) 7 class rectangle int width, length ; void set (intx,int y) Width = Length = y } eye ote in defined class has three members. two variabl/members and one method. DECLARING OBJECTS: An object is an instance of a class, Objects are created using “new” keyword. The “new” operator creates an object of the specified class, allocates memory dynamically and returns a reference to that object. This reference is the address of the object. The following is the general form to create an object. class-name object-name; object-name = new class-name(); The above two steps can be combined in one step as follows: class-name object-name=new class-name( ); Example :- class Rectangle int length; Scanned with CamScanner Prepared By Khadar 9966648277 int width; x, int y) length=x; widt! void show( ) { system.out println(“length= “#length) ; System.out.printin("width= “twidth); ) class test { Public static void main(String args[]) { Rectangle obj = new Rectangle(); obj.getData (50,10); obj.show( ); } } METHODS: ‘A method is a block of statements, that performs a particular task. Methods are defined inside the body of the class. The general form of method is: return-type method-name (parameter-list) { //pody of the method } Here, “return-type” specifies the type of data returned by the method. This can be any valid type, including a class type. If the method does not return any value, its return-type must be void. The “method-name” can be any legal identifier. The “parameter-list” is a sequence of type and variables pairs separated by commas. If the method has no parameters, then the parameter list is empty. Methods that have a return-type other than void returns a value to the calling function using the following syntax : return value; Scanned with CamScanner oF Prepared By Khadar 99666, Here “return” is the keyword and “value” is the value to be returned. SONSTRUCTORS: Constructors are special methods that are used to initialize an object when it is created. It has the same name as that of its cl lass and is syntactically similar to a method. Some important features of a constructor are : ~ Constructors do not have a return type, not even void. Y Constructors can be overloaded like methods. Y Aconstructor is call ‘ed implicitly when an object of that class is created, ¥ When no construct 'or is defined, a default Constructor is provided by the compiler. Example :- class rectangle { int width, length ; Rectangle( ) //default constructor { Width= length=0; } Rectangle (intx, inty) //parameterized constructor { Width Length } } If we create an object as, RectangleobjtnewRectangle(); //ca11s aetavie constructor Rectangleobj*newRectangle (10,20) + //calisparaneterized constructor STATIC: when a member is declared “static”, it can be accessed independently of any object. We can declare both methods and variables to be static. ‘When objects of its class are created, no copy of a static variable is made. All objects of that class share same static variables. A method declared as static can be called without the help of any object. A static method has some restrictions. Scanned with CamScanner Prepared By Khadar 9966648277 ¥ They can call only other static methods. v They can access only static variables. ¥ They cannot refer to “this” or “super”. ‘A block of statements can also be declared as static . Such a block is executed only once when the class is loaded. It is not executed for every object. Example :- class demo staticint staticint b; static void show( ) { pyatem.out-printin(*a="+at"-" 4h)! } static { // static block b = ak47 } public static void main(String args[]) ( show ()7 } ACCESS CONTROL: fan “access specifier” is used to specify how a member can be accessed . Java's access specifiers are public, private and protected. Java also has a default access level. When a member is declared as public, then that member can be accessed by any other code in the program. When a member is declared as private, then that member can only be accessed by other members of its class. “protected” members accessed by any member in the same package and sub class of other package. When no access specifiers is used , it results in default access level. Default members accessible within the package. Example = Scanned with CamScanner Prepared By Khadar 99666qq class Test int a; // default access level publicint b; privateint c; } class access { Public static void mai n (String args(]) { Test ob = new Test () ob.a =10; ob. // these two works properly ; ob. //gives an error because ¢ is private ? THIS:- The “this” keyword is used to refer the object that invoked it. “this” can be method to refer to the current object. used inside any Syntax : this.member; Instance variable hiding:- sometimes the names of instance variables and the names of the formal Parameters of a method in that class may be same. In such a case, the instance variables are hidden by formal parameters. To access the hidden instance variables “this” can be used. Example :- class Rectangle { int length, width; Rectangle () { Length =width =0; } Rectangle (intlength, intwidth) //thisnidesinstancevariables { Scanned with CamScanner SS % \ Prepared By Khadar 9966648277 ® this.length = length; atance varlable /longth refers to fornal paraneters sthis,length refers to inatan this.width = width; ) GARBAGE COLLECTION == Objects are created dynamically by using the “new ” operator. Senay ieee deallocated when they are no longer needed. In c++, this is done using jelete” operator. But in java, there is no such operator. Java handles deallocation automatically. The technique that do this is called garbage collection. Garbage collection occurs at regular intervals during the execution of a program. when an object goes out scope, its memory is deallocated. OVERLOADING METHODS :- Overloading methods means to define two or more methods within the same class that share the same name. Method overloading is one of the ways that java implements polymorphism. Overloaded methods must differ in type and / or number of their Parameters. When java encounters a call to an overloaded method, it executes the method whose parameter match the arguments used in the call. if more than one match is found then it gives an error. If no exact match is found then j java uses implicit type conversion of arguments. . Example :- class demo { void test () { System.out.println(“no parameters”) . } void te§t (int x) { System.out.print1n (“x="+x) ; } void test(int x, int y) Scanned with CamScanner Prepared By Khadar 996648; System.out.println("x="+ x +”y= “ty)i j void test (double x) U System.out.println ("x= "+x) 7 { Public static void main(String args(]) { Demo obj= new Demo(); obj.test(); obj.test (100) ; obj.test (100, 200); obj.test (123.4); } class test | | | } VET ct :- Like normal methods, constructors can also be Joverloaded. Overloaded constructors must have different type and/or number of. arguments. When an object is created, the constructor that matches the arguments is 5 | invoked. / \ Example C class Rectangle { int length, width; Rectangle () { Length= width= | } | Rectangle(int x) { | Length = width = x; | } Scanned with CamScanner Prepared By Khadar 9966648277 rectangle(int x , int y ) 1 Length=x; Width= 3 class test { — Public static void main (String args[]}) Rectangle rl = new rectangle();// ealts 1" Rectangle r2 = new rectangle (10); Rectangle r2@= new rectangle (10,20) ¢// calls 3rd constructor } ec * constructor // calls 2nd constructor ‘There are two ways that a prog and call-by-reference. In call-by-value, formal parameter. The changes made argument used to call it. the method copies the value of an argument into the to the parameter of the method does not affect the. In call-by-reference, a reference to an argument is passed to the parameter. This reference is used to access the actual argument specified in the call. The changes made. to the parameter will affect the argument used to call it. |n java, when simple types are passed to a method, itis passed by value. Example :- class Test { void swap(int x, int y) { int temp=x; x=y; y=temp; } } class Demo Scanned with CamScanner Prepared By khaday Public static void main(String args{]) Test obj = now Test (); int a=10, b=20; System.out.printin (Mz >bj.swap (a,b); System. out.print1n("a="ta+"b="+b) ; ) } The o/p from the above program is a=10 b=20 a=10 b=20 0, the changes made to the formal parameters does not affect the actual arguments When an object is passed to a method, itis passed by reference. Changes to the object inside the method affects the object used as the argument. Example class Test { inta,b; Test (int { a=x; bey; } void swap( test obj) { int temp = obj.a; Obj .a=obj..b; Obj .b=temp; Scanned with CamScanner prepared By Khadar 9966648277 = pomo plic static void main(Strin args(1) pub: al new Test (10,20); vprint1n (“a="+obj.at"b="tobj .b) 7 obs tem. out ap (ob5) + tem. out .print1n(*a="+obj .at"b="+tobj -b) , The o/p of the above program will be a=10 b=20 a=20 b=10 Recursion is the process of defining something in terms of itself. In java, recursion is the property that allows a method to call itself. A method that calls itself is called recursive. Example: classFactorical { int fact (int n) { if(n==1) return 1; Return (n*fact (n-1) ); } } lass Recursion Public static void main(String Scanned with CamScanner Prepared By Khadar 9966648277. Factorial fact=new Factorial (); System.out.println("result = “#f£.fact (5)); ) ) In recursive methods, there must be a condition somewhere in the method to return without the recursive call being executed, Recursive methods use stack to store local variables and parameters. Recursive functions may execute somewhat slower due to the overhead of stack management. The main advantage of recursion js that it can be used to create clear and simple programs of several complex algorithms. Scanned with CamScanner

You might also like