II-I-OOPS Lecture Notes PDF

Summary

These lecture notes cover fundamental concepts of object-oriented programming(OOP) and provide an introduction to Java. It touches upon the history and principles of Java, different editions like J2SE/JSE, J2EE/JEE, J2ME/JME, and JavaFX, along with OOP concepts like objects and classes, inheritance, and polymorphism.

Full Transcript

Unit-1 Introduction: Introduction to Object Oriented Programming, The History and Evolution of Java, Introduction to Classes, Objects, Methods, Constructors, this keyword, Garbage Collection, Data Types, Variables, Type Conversion and Casting, Arrays, Operators, Control Statements, Method Overloadi...

Unit-1 Introduction: Introduction to Object Oriented Programming, The History and Evolution of Java, Introduction to Classes, Objects, Methods, Constructors, this keyword, Garbage Collection, Data Types, Variables, Type Conversion and Casting, Arrays, Operators, Control Statements, Method Overloading, Constructor Overloading, Parameter Passing, Recursion, String Class and String handling methods. History of Java:- Java is a popular object-oriented programming language, developed by sun micro systems of USA in 1991(which has since been acquired by oracle). Originally it was called as oak. The developers of java are James Gosling and his team (Patrick naughton, Chris warth, ed frank, and mike Sheridan). This language was renamed as “java” in 1995. Java was publicly announced in 1995 and now more than 3 billion devices run java The primary motivation of java was need for a platform independent language which can be used to create software to be embedded in different consumer electronic devices like remote controls, microwave ovens etc. JDK 1.0 was released on January 23, 1996. After the first release of Java, there have been many additional features added to the language. Now Java is being used in Windows applications, Web applications, enterprise applications, mobile applications, cards, etc. Each new version adds new features in Java. Principles There were five primary goals in the creation of the Java language: 1. It must be simple, object-oriented, and familiar. 2. It must be robust and secure. 3. It must be architecture-neutral and portable. 4. It must execute with high performance. 5. It must be interpreted, threaded, and dynamic. Editions:  Java Standard Edition: - Java Standard Edition, also known as J2SE / JSE is the java platform (Any hardware or software environment in which a program runs is known as a platform.) for developing client-side application which runs on desktop, and applets which run on web browser. Core Java + JDBC is the part of Java Standard Edition (J2SE / JSE).  Java Enterprise Edition : - Java Enterprise Edition, also known as J2EE / JEE is the java platform built on the top of Java SE , which is used to develop enterprise- oriented server applications.(Server side applications include servlets, which are java programs that are similar to applets but run on a server rather than a client.) Servlets + JSPs are the part of Java Enterprise Edition.  Java Micro Edition: - Java Micro Edition, also known as J2ME / JME is the java platform which is also built on Java SE. It is mainly used to develop mobile applications.  Java FX: - Java FX, also known as Java Flex is used to develop rich internet applications. It uses light-weight user interface API. Introduction to Object Oriented Programming:- Object-oriented programming (OOP) is a programming paradigm based on the concept of objects, which are data structures that contain data, in the form of fields (or attributes) and code, in the form of procedures, (or methods). Characteristics of OOP:  Emphasis on data.  Programs are divided into what are known as methods.  Data structures are designed such that they characterize the objects.  Methods that operate on the data of an object are tied together.  Data is hidden.  Objects can communicate with each other through methods.  Reusability.  Follows bottom-up approach in program design OOP concepts: Object-Oriented Programming is a methodology or paradigm to design a program using classes and objects. It simplifies software development and maintenance by providing some concepts: o Object o Class o Inheritance o Polymorphism o Abstraction o Encapsulation Object: Any entity that has state and behavior is known as an object. For example, a chair, pen, table, keyboard, bike, etc. It can be physical or logical. An Object can be defined as an instance of a class. An object contains an address and takes up some space in memory. Objects can communicate without knowing the details of each other's data or code. The only necessary thing is the type of message accepted and the type of response returned by the objects. Example: A dog is an object because it has states like color, name, breed, etc. as well as behaviors like wagging the tail, barking, eating, etc. Class: Collection of objects is called class. It is a logical entity. A class can also be defined as a blueprint from which we can create an individual object. Class doesn't consume any space. Inheritance When one object acquires all the properties and behaviors of a parent object, it is known as inheritance. It provides code reusability. It is used to achieve runtime polymorphism. Polymorphism: Polymorphism means taking many forms, where ‘poly’ means many and ‘morph’ means forms. It is the ability of a variable, function or object to take on multiple forms. In other words, polymorphism allows us to define one interface or method and have multiple implementations. For eg, Bank is a base class that provides a method rate of interest. But, rate of interest may differ according to banks. For example, SBI, ICICI and AXIS are the child classes that provide different rates of interest. Polymorphism in Java is of two types:  Run time polymorphism  Compile time polymorphism Abstraction: Abstraction is a process of hiding the implementation details and showing only functionality to the user. Another way, it shows only essential things to the user and hides the internal details, for example, sending SMS where you type the text and send the message. You don't know the internal processing about the message delivery. Abstraction means simple things like objects, classes, and variables represent more complex underlying code and data. It avoids repeating the same work multiple times. In java, we use abstract class and interface to achieve abstraction. Abstract class: Abstract class in Java contains the ‘abstract’ keyword. If a class is declared abstract, it cannot be instantiated. So we cannot create an object of an abstract class. Also, an abstract class can contain abstract as well as concrete methods. To use an abstract class, we have to inherit it from another class where we have to provide implementations for the abstract methods there itself, else it will also become an abstract class. Interface: Interface in Java is a collection of abstract methods and static constants. In an interface, each method is public and abstract but it does not contain any constructor. Along with abstraction, interface also helps to achieve multiple inheritances in Java. So an interface is a group of related methods with empty bodies. Encapsulation: Encapsulation is the mechanism that binds together code and the data it manipulates, and keeps both safe from outside interference and misuse.  In Java, the basis of encapsulation is the class. There are mechanisms for hiding the complexity of the implementation inside the class.  Each method or variable in a class may be marked private or public.  The public interface of a class represents everything that external users of the class need to know, or may know.  The private methods and data can only be accessed by code that is a member of the class.  Therefore, any other code that is not a member of the class cannot access a private method or variable.  Since the private members of a class may only be accessed by other parts of program through the class’ public methods, we can ensure that no improper actions take place. Features of java: The features of Java are also known as Java buzzwords. A list of most important features of java language is given below 1. Simple 2. Object-Oriented 3. Portable 4. Platform independent 5. Secured 6. Robust 7. Architecture neutral 8. Interpreted 9. High Performance 10. Multithreaded 11. Distributed 12. Dynamic Simple: Its coding style is very clean and easy to understand.  Java syntax is base on c++.  Java has removed many complicated and rarely used features, for example  Concept of Explicit Pointers  Storage classes  Preprocessors and header files  Multiple Inheritance  Operator Overloading  Goto Statements  There is no need to remove unreferenced objects because there is an automatic garbage collection in java. Object-Oriented: Java is an object-oriented programming language. Everything in Java is an object. Object-oriented means we organize our software as a combination of different types of objects that incorporate both data and behavior. Object-oriented programming (OOPs) is a methodology that simplifies software development and maintenance by providing some rules. Basic concepts of OOPs are: 1. Object 2. Class 3. Inheritance 4. Polymorphism 5. Abstraction 6. Encapsulation Portable: Java is portable because it facilitates us to carry the Java byte code to any platform. It doesn't require any implementation. Moreover, any changes and updates made in Operating Systems, Processors and System resources will not enforce any changes in Java programs. Platform Independent Being platform-independent means a program compiled on one machine can be executed on any machine in the world without any change. Java achieves platform independence by using the concept of the BYTE code. There are two types of platforms software-based and hardware based. Java provides a software based platform. Java has two components: 1. Runtime environment 2. API(Application programming language) Java code can run on multiple platforms, for example Windows, Linux, Solaris, Mac Os, etc. Java converts the source code into an intermediate code called the bytecode. This byte code is further translated to machine-dependent code by another layer of software called JVM (Java Virtual Machine). Java is a “Write Once, run anywhere” (WORA) which means that we can develop applications on one environment (OS) and run on any other environment without doing any modification in the code. Below diagram explains the platform independence feature of Java-Portable Secured: Java is best known for its security. With Java , we can develop virus free systems. Java is secured because:  No explicit pointer  Java programs run inside a virtual machine sandbox.  Class loader: Class loader in java is part of Java Runtime Environment (JRE) which is used to load java classes into Java Virtual Machine dynamically. It adds security by separating the package for the classes of local file system from those that are imported from network sources.  Byte code Verifier: It checks the code fragments for illegal code that can violate access right to objects.  Security Manager: It determines what resources a class can access such as reading and writing to the local disk. Robust: Robust simply means strong. Java is robust beacuase:  Java has a strong memory management system. It helps in eliminating errors as it checks the code during both compile and runtime.  There is a lack of pointers that avoid security problems.  Java is garbage-collected language – JVM automatically deallocates the memory blocks and programmers do not have to worry about deleting the memory manually as in case of C/C++.  Java also provides the concept of exception handling which identifies runtime errors and eliminates them. Architecture neutral: Java is architecture neutral because there are no implementation dependent features, for example, the size of primitive types is fixed. In C programming, int data type occupies 2 bytes of memory for 32-bit architecture and 4 bytes of memory for 64-bit architecture. However, it occupies 4 bytes of memory for both 32 and 64-bit architectures in Java. Interpreted: Java is both compiled and interpreted language since java programs are compiled first using java compiler (javac) then at runtime the compiled code (bytecode) is interpreted by java interpreter in order to execute the program. Java is a highly interpreted language. At runtime java bytecode is interpreted(converted) into machine code using java interpreter(part of JVM) in order to run the program. Java has the feature of just- in-time(JIT) compilation (happens at runtime) which reduces the interpretation time. The diagram below shows the above process: High Performance: Java is faster than other traditional interpreted programming languages because Java bytecode is "close" to native code. It is still a little bit slower than a compiled language (e.g., C++). Java is an interpreted language that is why it is slower than compiled languages, e.g., C, C++, etc. Java provides high performance with the use of “JIT – Just In Time compiler”, in which the compiler compiles the code on-demand basis, that is, it compiles only that method which is being called. This saves time and makes it more efficient. Multithreaded: A thread is like a separate program, executing concurrently. We can write Java programs that deal with many tasks at once by defining multiple threads. The code of java is divided into smaller parts and Java executes them in a sequential and timely manner.  The main advantage of multithreading is that the maximum utilization of resources is possible.  It doesn’t occupy memory for each thread. It shares a common memory area.  There is no need to wait for the application to finish one task before beginning another one.  There is a decreased cost of maintenance. Also, It is time-saving. It improves the performance of complex applications. Distributed: Java is distributed because it encourages users to create distributed applications. RMI (Remote Method Invocation) and EJB (Enterprise JavaBeans) are used for creating distributed applications. This feature of Java makes us able to access files by calling the methods from any machine on the internet. It also enables multiple programmers at many locations to work together on a single project. Dynamic and Extensible: Java is a dynamic language. It supports the dynamic loading of classes. It means classes are loaded on demand. It also supports functions from its native languages, i.e., C and C++. Java supports dynamic compilation and automatic memory management (garbage collection). Java is dynamic and extensible means with the help of OOPs, we can add classes and add new methods to classes, creating new classes through subclasses. This makes it easier for us to expand our own classes and even modify them. Java even supports functions written in other languages such as C and C++ to be written in Java programs. These functions are called “native methods”. These methods are dynamically linked at runtime. WRITING SIMPLE JAVA PROGRAM: A java program may contain many classes, of which only one class should contains main() method. Documentation section Suggested Package statements Optional Import statements Optional Interface statements Optional Class Definations Optional Main Method Class { Essential Main Method Definations } Documentation section: It consists of comment lines( program name, author, date,…….), // - for single line comment. - multiple line comments. - known as documentation comment, which generated documentation automatically. Package statement: This is the first statement in java file. This statement declares a package name and informs the compiler that the class defined here belongs to this package. Ex: - package student Import statements: This is the statement after the package statement. It is similar to # include in c/c++. Ex: import java.lang.String The above statement instructs the interpreter to load the String class from the lang package. Note: Import statement should be before the class definitions. A java file can contain N number of import statements. Interface statements: An interface is like a class but includes a group of method declarations. Note: Methods in interfaces are not defined just declared. Class definitions: Java is a true oop, so classes are primary and essential elements of java program. A program can have multiple class definitions. Main method class: Every stand-alone program required a main method as its starting point. As it is true oop the main method is kept in a class definition. Every stand-alone small java program should contain at least one class with main method definition. A Simple Java Program: In this section, we will learn how to write the simple program of Java. We can write a simple hello Java program easily after installing the JDK. To create a simple Java program, we need to create a class that contains the main method. Let's understand the requirement first. Requirements: For executing any Java program, the following software or application must be properly installed. o Install the JDK if you don't have installed it, download the JDK and install it. o Set path of the jdk/bin directory. http://www.javatpoint.com/how-to-set-path-in-java o Create the Java program o Compile and run the Java program Creating Hello World Example: Let's create the hello java program: class Simple{ public static void main(String args[]){ System.out.println("Hello Java"); } } Save the above file as Simple.java. To compile: javac Simple.java To execute: java Simple Output: Hello Java Compilation Flow: When we compile Java program using javac tool, the Java compiler converts the source code into byte code. Parameters used in First Java Program: Let's see what is the meaning of class, public, static, void, main, String[], System.out.println(). o class keyword is used to declare a class in Java. o public keyword is an access modifier that represents visibility. It means it is visible to all. o static is a keyword. If we declare any method as static, it is known as the static method. The core advantage of the static method is that there is no need to create an object to invoke the static method. The main() method is executed by the JVM, so it doesn't require creating an object to invoke the main() method. So, it saves memory. o void is the return type of the method. It means it doesn't return any value. o main represents the starting point of the program. o String[] args or String args[] is used for command line argument. o System.out.println() is used to print statement. Here, System is a class, out is an object of the PrintStream class, println() is a method of the PrintStream class. Rules for writing JAVA programs:  Every statement ends with a semicolon  Source file name and class name must be the same.  It is a case-sensitive language.  Everything must be placed inside a class, this feature makes JAVA a true object oriented programming language. Rules for file names:  A source code file can have only one public class, and the file name must match the public class name.  A file can have more than one non-public class.  Files with no public classes have no naming restriction Java Comments: The java comments are statements that are not executed by the compiler and interpreter. The comments can be used to provide information or explanation about the variable, method, class or any statement. It can also be used to hide program code for specific time. Types of Java Comments There are 3 types of comments in java. 1. Single Line Comment 2. Multi Line Comment 3. Documentation Comment Java Single Line Comment: The single line comment is used to comment only one line. Syntax: //This is single line comment Example: public class CommentExample1 { public static void main(String[] args) { int i=10;//Here, i is a variable System.out.println(i); }} Output: 10 Java Multi Line Comment: The multi line comment is used to comment multiple lines of code. Syntax: Example: public class CommentExample2 { public static void main(String[] args) { int i=10; System.out.println(i); }} Output: 10 Java Documentation Comment: The documentation comment is used to create documentation API. To create documentation API, you need to use javadoc tool. Syntax: Example: public class Calculator { public static int add(int a, int b) { return a+b; } public static int sub(int a, int b) { return a-b; }} Compile it by javac tool: javac Calculator.java Create Documentation API by javadoc tool: javadoc Calculator.java Now, there will be HTML files created for our Calculator class in the current directory. Open the HTML files and see the explanation of Calculator class provided through documentation comment. Data type: Java is a statically typed and also a strongly typed language. In Java, each type of data (such as integer, character, hexadecimal, etc. ) is predefined as part of the programming language and all constants or variables defined within a given program must be described with one of the data types. Data types represent the different values to be stored in the variable. In java, there are two categories of data types:  Primitive data types  Non-primitive data types Figure: Data types in java Literals: A literal represents a value that is stored into a variable directly in the program For example: boolean=false; char gender=’F’; short s=1000; int i=-1256; In the preceding statements, the right hand side values are called literals because these values are being stored into the variables shown at the left hand side. As the data type of the variable changes, the type of the literals also changes. So we have different types of literals. There are as follows:  Integer literals  Float literals  Character literals  String literals  Boolean literals Variable: A variable is the name of a reserved area allocated in memory. In other words, it is a name of the memory location. It is a combination of "vary + able" which means its value can be changed. Types of Variable There are three types of variables in java:  Local variable  Instance variable  Static variable Local variable:  A variable declared inside the body of the method is called local variable. You can use this variable only within that method and the other methods in the class aren't even aware that the variable exists.  Local variables are declared inside the methods, constructors, or blocks.  Local variables are created when the method, constructor or block is entered.  Local variable will be destroyed once it exits the method, constructor, or block.  Local variables are visible only within the declared method, constructor, or block.  Local variables are implemented at stack level internally. There is no default value for local variables, so local variables should be declared and an initial value should be assigned before the first use.  Access specifiers cannot be used for local variables.  A local variable cannot be defined with "static" keyword. Instance variable:  A variable declared inside the class but outside the method, is called instance variable.  Instance variables are declared in a class, but outside a method, constructor or any block.  A slot for each instance variable value is created when a space is allocated for an object in the heap.  Instance variables are created when an object is created with the use of the keyword ‘new’ and destroyed when the object is destroyed.  Instance variables hold values that must be referenced by more than one method, constructor or block, or essential parts of an object’s state that must be present throughout the class.  Access modifiers can be given for instance variables.  The instance variables are visible for all methods, constructors and block in the class. It is recommended to make these variables as private. However, visibility for subclasses can be given for these variables with the use of access modifiers.  Instance variables have default values.  numbers, the default value is 0,  Booleans it is false,  Object references it is null.  Values can be assigned during the declaration or within the constructor.  Instance variables cannot be declared as static.  Instance variables can be accessed directly by calling the variable name inside the class. However, within static methods (when instance variables are given accessibility), they should be called using the fully qualified name: ObjectReference.VariableName. Static Variable:  Class variables also known as static variables are declared with the static keyword in a class, but outside a method, constructor or a block.  Only one copy of each class variable per class is created, regardless of how many objects are created from it.  Static variables are rarely used other than being declared as constants. Constants are variables that are declared as public/private, final, and static. Constant variables never change from their initial value  Static variables are stored in the static memory. It is rare to use static variables other than declared final and used as either public or private constants.  Static variables are created when the program starts and destroyed when the program stops.  Visibility is same as instance variables. However, most static variables are declared public since they must be available for users of the class.  Default values are same as instance variables.  Values can be assigned during the declaration or within the constructor. Additionally, values can be assigned in special static initialize blocks.  Static variables cannot be local.  Static variables can be accessed by calling with the class name like ClassName.VariableName.  When declaring class variables as public static final, then variable names (constants) are all in upper case. If the static variables are not public and final, the naming syntax is the same as instance and local variables. Example: class VaribleDemo { int a=10; //instance variable static int b=20; //static variable or class variable VaribleDemo() { int c =30; //Local variables System.out.println("c="+c); } void setData() { int d=40; //Local varibles System.out.println("d="+d); } public static void main(String args[]) { VaribleDemo v=new VaribleDemo(); System.out.println("a="+v.a); System.out.println("b="+b); v.setData(); } } Output: ELEMENTS OR TOKENS IN JAVA PROGRAM: A token is the smallest element of a program that is meaningful to the compiler. Tokens can be classified as follows:  Keywords  Identifiers  Constants  Special Symbols  Operators Keyword: Keywords are pre-defined or reserved words in a programming language. Each keyword is meant to perform a specific function in a program. Since keywords are referred names for a compiler, they can’t be used as variable names because by doing so, we are trying to assign a new meaning to the keyword which is not allowed. Java language supports following keywords: abstract assert boolean break byte case catch char class const continue default do double else enum exports extends final finally float for goto if implements import instanceof int interface long module native new open opens package private protected provides public requires return short static strictfp super switch synchronized this throw throws to transient transitive try uses void volatile while with Identifiers: Identifiers used for naming classes, methods, variables, objects, labels and interfaces in a program. Java identifiers follow the following rules: 1. Identifier must start with a letter, a currency character ($), or a connecting character such as underscore (_). 2. Identifier cannot start with a number. 3. Uppercase and lowercase letters are distinct. 4. Total, TOTAL and total are different. 5. They can be of any length. 6. It should not be a keyword. 7. Spaces are not allowed. Examples of legal and illegal identifiers follow, first some legal identifiers:  int _a;  int $c;  int ______2_w;  int _$;  int this_is_a_very_detailed_name_for_an_identifier; The following are illegal (Recognize why): 1. int :b; 2. int -d; 3. int e#; 4. int.f; Conventions for identifier names: 1. Names of all public methods and instance variables start with lowercase, for more than one word second word’s first character shold be capital. Ex:- total(), display(), totalMarks, netSalary(), getData() 2. All classes and interfaces should start with capital letter, for more then one word the second word’s first character should be capital. Ex:- Student, HelloJava 3. Constant variables should be in capital letters and for more than one word underscore is used. Ex:- MAX, TOTAL_VALUE 4. Package name should be in lowercase only. Ex:- mypack Constants in Java: A constant is a variable which cannot have its value changed after declaration. It uses the 'final' keyword. Syntax: Modifier final dataType variableName = value; //variable constant Modifier static final dataType variableName = value; //constant variable Special Symbols: The following special symbols are used in Java having some special meaning and thus, cannot be used for some other purpose. [] () {}, ; * = 1. Brackets[]: Opening and closing brackets are used as array element reference. These indicate single and multidimensional subscripts. 2. Parentheses(): These special symbols are used to indicate function calls and function parameters. 3. Braces{}: These opening and ending curly braces marks the start and end of a block of code containing more than one executable statement. 4. Comma (, ): It is used to separate more than one statements like for separating parameters in function calls. 5. Semicolon: It is an operator that essentially invokes something called an initialization list. 6. Assignment operator: It is used to assign values Operators: Operator in java is a symbol that is used to perform operations. Java provides a rich set of operators to manipulate variables. For example: +, -, *, / etc. All the Java operators can be divided into the following groups Arithmetic Operators:  Multiplicative : * / %  Additive : + - Relational Operators  Comparison : < > =  instanceof  Equality : == != Bitwise Operators  bitwise AND : &  bitwise exclusive OR : ^  bitwise inclusive OR : |  Shift operator: > >>> Logical Operators  logical AND : &&  logical OR : ||  logical NOT : ~ ! Assignment Operators: = Ternary operator: ? : Unary operator  Postfix : expr++ exp--  Prefix : ++expr --expr +expr -expr Type Casting/type conversion: Converting one primitive datatype into another is known as type casting (type conversion) in Java. We can cast the primitive datatypes in two ways namely, Widening and, Narrowing. Widening − Converting a lower datatype to a higher datatype is known as widening. In this case the casting/conversion is done automatically therefore, it is known as implicit type casting. In this case both datatypes should be compatible with each other. Example public class WideningExample { public static void main(String args[]){ char ch = 'C'; int i = ch; System.out.println(i); } Output Integer value of the given character: 67 Narrowing − Converting a higher datatype to a lower datatype is known as narrowing. In this case the casting/conversion is not done automatically, We need to convert explicitly using the cast operator “( )” explicitly. Therefore, it is known as explicit type casting. In this case both datatypes need not be compatible with each other. Example import java.util.Scanner; public class NarrowingExample { public static void main(String args[]){ Scanner sc = new Scanner(System.in); System.out.println("Enter an integer value: "); int i = sc.nextInt(); char ch = (char) i; System.out.println("Character value of the given integer: "+ch); } } Output Enter an integer value: 67 Character value of the given integer: C Java Enum: Enum in java is a data type that contains fixed set of constants. It can be used for days of the week (SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY and SATURDAY) , directions (NORTH, SOUTH, EAST and WEST) etc. The java enum constants are static and final implicitly. It is available from JDK 1.5. Java Enums can be thought of as classes that have fixed set of constants. Simple example of java enum class EnumExample1 { public enum Season { WINTER, SPRING, SUMMER, RAINY }; public static void main(String[] args) { for (Season s : Season.values()) System.out.println(s); } } Output: WINTER SPRING SUMMER RAINY Control flow Statements: In java, the default execution flow of a program is a sequential order. But the sequential order of execution flow may not be suitable for all situations. Sometimes, we may want to jump from line to another line, we may want to skip a part of the program, or sometimes we may want to execute a part of the program again and again. To solve this problem, java provides control statements. Types of Control Statements In java, the control statements are classified as follows.  Selection Control Statements ( Decision Making Statements )  Iterative Control Statements ( Looping Statements )  Jump Statements Let's look at each type of control statements in java. Selection Control Statements In java, the selection statements are also known as decision making statements or branching statements. The selection statements are used to select a part of the program to be executed based on a condition. Java provides the following selection statements.  if statement  if-else statement  if-else if statement  nested if statement  switch statement Example: import java.util.Scanner; public class IfElseDemo { public static void main(String[] args) { Scanner read = new Scanner(System.in); System.out.print("Enter any number: "); int num = read.nextInt(); if((num % 2) == 0) { System.out.println("Given number is EVEN number!!"); } else { System.out.println("Given number is ODD number!!"); } } } Iterative Control Statements In java, the iterative statements are also known as looping statements or repetitive statements. The iterative statements are used to execute a part of the program repeatedly as long as the given condition is True. Using iterative statements reduces the size of the code, reduces the code complexity, makes it more efficient, and increases the execution speed. Java provides the following iterative statements.  while statement  do-while statement  for statement  for-each statement Example: public class ForEachTest { public static void main(String[] args) { int[] arrayList = {10, 20, 30, 40, 50}; for(int i : arrayList) { System.out.println("i = " + i); } System.out.println("Statement after for-each!"); }} Jump Statements In java, the jump statements are used to terminate a block or take the execution control to the next iteration. Java provides the following jump statements.  break  continue  return break: Continue: Introduction of classes: A class is a group of objects which have common properties. It is a template or blueprint from which objects are created. It is a logical entity. It can't be physical. A class in Java can contain: o Fields o Methods o Constructors o Blocks o Nested class and interface General form of class: A class is declared by use of the class keyword. The general form of a class definition is shown here: class ClassName { VariableDeclaration-1; VariableDeclaration-2; VariableDeclaration-3; ------------------------ ------------------------ VariableDeclaration-n; returnType methodname-1([parameters list]) { body of the method… } returnType methodname-2([parameters list]) { body of the method… } ------------------------ ------------------------ returnType methodname-3([parameters list]) { body of the method… } }// end of class The data, or variables, defined within a class are called instance variables. The code is contained within methods. Collectively, the methods and variables defined within a class are called members of the class. In most classes, the instance variables are acted upon and accessed by the methods defined for that class. Thus, it is the methods that determine how a class’ data can be used. Example: class Demo { int x=5; void display() { System.out.println(“x value is: ”+x); }} Creating Objects: An object in Java is essentially a block of memory that contains space to store all the instance variables. Creating an object also known as instantiating an object. Objects in Java are created using the new operator. The new operator creates an object of the specified class and returns a reference to that object. Syntax for object creation: classname objectname; //declares a variable to hold the object reference objectname = new classname( ); // Assigns the object reference to the variable Accessing class Members: To access members (fields and the methods) of an object use the dot (.) operator together with the reference to an object. The general syntax is as follows: objectname.variablename; objectname.methodname(parameter-list); Example: class Demo { int x; int display() { System.out.println("X value is: "+x); return 0; } public static void main(String args[]) { Demo D1=new Demo(); D1.x=10; D1.display(); } } Output: X value is: 10 Assigning Object Reference Variables When you assign one object reference variable to another object reference variable, we are not creating a copy of the object; we are only making a copy of the reference Student s1=new Student(); Student s2=s1; s1 Name: null Student Objects s2 Idno: 0 class Student { String name; int idno; public static void main(String args[]) { Student s1=new Student();//create and initialize object //Assigning Object Reference Variables Student s2=s1; System.out.println("Name: "+s2.name); System.out.println("Idno: "+s2.idno); } } Output: Name: null Idno: 0 Methods in java: A method is a block of code or collection of statements or a set of code grouped together to perform a certain task or operation. It is used to achieve the reusability of code. We write a method once and use it many times. We do not require to write code again and again. It also provides the easy modification and readability of code, just by adding or removing a chunk of code. The method is executed only when we call or invoke it. Method Declaration The method declaration provides information about method attributes, such as visibility, return-type, name, and arguments. It has six components that are known as method header, as we have shown in the following figure. Method Signature: Every method has a method signature. It is a part of the method declaration. It includes the method name and parameter list. Access Specifier: Access specifier or modifier is the access type of the method. It specifies the visibility of the method. Java provides four types of access specifier: o Public: The method is accessible by all classes when we use public specifier in our application. o Private: When we use a private access specifier, the method is accessible only in the classes in which it is defined. o Protected: When we use protected access specifier, the method is accessible within the same package or subclasses in a different package. o Default: When we do not use any access specifier in the method declaration, Java uses default access specifier by default. It is visible only from the same package only. Return Type: Return type is a data type that the method returns. It may have a primitive data type, object, collection, void, etc. If the method does not return anything, we use void keyword. Method Name: It is a unique name that is used to define the name of a method. It must be corresponding to the functionality of the method. Suppose, if we are creating a method for subtraction of two numbers, the method name must be subtraction(). A method is invoked by its name. Parameter List: It is the list of parameters separated by a comma and enclosed in the pair of parentheses. It contains the data type and variable name. If the method has no parameter, left the parentheses blank. Method Body: It is a part of the method declaration. It contains all the actions to be performed. It is enclosed within the pair of curly braces. Types of Method There are two types of methods in Java: o Predefined Method o User-defined Method Predefined Method In Java, predefined methods are the method that is already defined in the Java class libraries is known as predefined methods. It is also known as the standard library method or built-in method. We can directly use these methods just by calling them in the program at any point. Some pre-defined methods are length(), equals(), compareTo(), sqrt(), etc. When we call any of the predefined methods in our program, a series of codes related to the corresponding method runs in the background that is already stored in the library. Each and every predefined method is defined inside a class. Such as print() method is defined in the java.io.PrintStream class. It prints the statement that we write inside the method. For example, print("Java"), it prints Java on the console. Example: public class Demo { public static void main(String[] args) { // using the max() method of Math class System.out.print("The maximum number is: " + Math.max(9,7)); } } Output: The maximum number is: 9is In the above example, we have used three predefined methods main(), print(), and max(). We have used these methods directly without declaration because they are predefined. The print() method is a method of PrintStream class that prints the result on the console. The max() method is a method of the Math class that returns the greater of two numbers. User-defined Method The method written by the user or programmer is known as a user-defined method. These methods are modified according to the requirement. How to Create a User-defined Method Let's create a user defined method that checks the number is even or odd. First, we will define the method. import java.util.Scanner; public class EvenOdd { public static void main (String args[]) { //creating Scanner class object Scanner scan=new Scanner(System.in); System.out.print("Enter the number: "); //reading value from user int num=scan.nextInt(); //method calling findEvenOdd(num); } //user defined method public static void findEvenOdd(int num) { //method body if(num%2==0) System.out.println(num+" is even"); else System.out.println(num+" is odd"); } } Output: Enter the number: 45 num is odd Constructor: A class contains constructors that are invoked to create objects from the class blueprint. Constructor declarations look like method declarations—except that they use the name of the class and have no return type. A constructor initializes an object immediately upon creation. Rules with Constructors  Constructor name must be the same as its class name  A Constructor must have no explicit return type  A Java constructor cannot be abstract, static, final, and synchronized  Constructors should be public.  Constructors cannot be inherited.  They can be overloaded. Many constructors with the same name can be defined. Types of Constructors: o Default constructor: is the type of constructor with out any argument. o Parameterized Constructor: is a constructor with one or more argument. Default Constructor: A constructor that have no parameter is known as default constructor. Syntax of default constructor: classname(){} Example of default constructor In this example, we are creating the no-arg constructor in the Bike class. It will be invoked at the time of object creation. Class Bike1 { Bike1(){ System.out.println("Bike is created"); } public static void main(String args[]) { Bike1 b=new Bike1(); }} Output:Bike is created Parameterized constructor: A parameterized constructor is a constructor that accepts some parameters. Any number of parameters can be specified. Parameterized constructors are mostly used to initialize the instance fields of a class. Example: class Demo { int num; String name; Demo() { System.out.print("default constructor"); } Demo(int n,String name1) { num=n; name=name1; } void display() { System.out.println(" "+num+" "+name); } } class ConstructorDemo { public static void main(String args[]) { Demo d=new Demo (); Demo d1=new Demo(1001,"shyam"); d.display(); d1.display(); } } Output: default constructor 0 null 1001 shyam Static Keyword The static keyword in Java is used for memory management mainly. We can apply static keyword with variables, methods, blocks and nested classes. The static keyword belongs to the class than an instance of the class. The static can be: o Variable (also known as a class variable) o Method (also known as a class method) o Block Static variable If you declare any variable as static, it is known as a static variable.  The static variable can be used to refer to the common property of all objects (which is not unique for each object), for example, the company name of employees, college name of students, etc.  The static variable gets memory only once in the class area at the time of class loading. Advantages of static variable It makes your program memory efficient (i.e., it saves memory). Understanding the problem without static variable class Student{ int rollno; String name; String college="SVREC"; } Suppose there are 500 students in our college, now all instance data members will get memory each time when the object is created. All students have its unique rollno and name, so instance data member is good in such case. Here, "college" refers to the common property of all objects. If we make it static, this field will get the memory only once. Example of static variable class Student{ int rollno;//instance variable String name; static String college ="SVREC";//static variable //constructor Student(int r, String n){ rollno = r; name = n; } //method to display the values void display (){System.out.println(rollno+" "+name+" "+college);} } //Test class to show the values of objects public class TestStaticVariable1{ public static void main(String args[]){ Student s1 = new Student(101,"Shyam"); Student s2 = new Student(102,"vinod"); //we can change the college of all objects by the single line of code //Student.college="SVREC"; s1.display(); s2.display(); } } Output: 101 Shyam SVREC 102 vinod SVREC Program of the counter without static variable and with static variable: //Java Program to demonstrate the use of an insta//Java Program to illustrate the use of static variab nce variable which get memory each time when le which is shared with all objects. we create an object of the class. class Counter{ class Counter{ static int count=0;//will get memory only once an int count=0;//will get memory each time when the d retain its value instance is created Counter(){ Counter(){ count++;//incrementing value count++;//incrementing the value of static variable System.out.println(count); } System.out.println(count); } public static void main(String args[]){ public static void main(String args[]){ //Creating objects //creating objects Counter c1=new Counter(); Counter c1=new Counter(); Counter c2=new Counter(); Counter c2=new Counter(); Counter c3=new Counter(); Counter c3=new Counter(); } } } } Output: Output: 1 1 1 2 1 3 Static method If you apply static keyword with any method, it is known as static method.  A static method belongs to the class rather than the object of a class.  A static method can be invoked without the need for creating an instance of a class.  A static method can access static data member and can change the value of it. Example of static method //Java Program to demonstrate the use of a static method. class Student{ int rollno; String name; static String college = "SVR Engg College"; //static method to change the value of static variable static void change(){ college = "SVREC"; } //constructor to initialize the variable Student(int r, String n){ rollno = r; name = n; } //method to display values void display(){ System.out.println(rollno+" "+name+" "+college); } } //Test class to create and display the values of object public class TestStaticMethod{ public static void main(String args[]){ Student.change();//calling change method //creating objects Student s1 = new Student(111,"Karan"); Student s2 = new Student(222,"Aryan"); Student s3 = new Student(333,"Sonoo"); //calling display method s1.display(); s2.display(); s3.display(); } } Output: 111 Karan SVREC 222 Aryan SVREC 333 Sonoo SVREC Restrictions for the static method There are two main restrictions for the static method. They are:  The static method cannot use non static data member or call non-static method directly.  this and super cannot be used in static context. class A{ int a=40;//non static public static void main(String args[]){ System.out.println(a); } } Output: Compile Time Error Q) Why is the Java main method static? Ans) Because the object is not required to call a static method. If it were a non-static method, JVM creates an object first then call main() method that will lead the problem of extra memory allocation. static block o Is used to initialize the static data member. o It is executed before the main method at the time of classloading. Example of static block class A2{ static{System.out.println("static block is invoked");} public static void main(String args[]){ System.out.println("Hello main"); } } Output: static block is invoked Hello main this Keyword There can be a lot of usage of Java this keyword. In Java, this is a reference variable that refers to the current object. Usage of Java this keyword: Here is given the 6 usage of java this keyword. 1. this can be used to refer current class instance variable. 2. this can be used to invoke current class method (implicitly) 3. this() can be used to invoke current class constructor. 4. this can be passed as an argument in the method call. 5. this can be passed as argument in the constructor call. 6. this can be used to return the current class instance from the method. 1. this can be used to refer current class instance variable. The this keyword can be used to refer current class instance variable. If there is ambiguity between the instance variables and parameters, this keyword resolves the problem of ambiguity. Understanding the problem without this keyword Let's understand the problem if we don't use this keyword by the example given below: class Student{ int rollno; String name; float fee; Student(int rollno,String name,float fee){ rollno=rollno; name=name; fee=fee; } void display(){System.out.println(rollno+" "+name+" "+fee);} } class TestThis1{ public static void main(String args[]){ Student s1=new Student(111,"ankit",5000f); Student s2=new Student(112,"sumit",6000f); s1.display(); s2.display(); }} Output: 0 null 0.0 0 null 0.0 In the above example, parameters (formal arguments) and instance variables are same. So, we are using this keyword to distinguish local variable and instance variable. Solution of the above problem by this keyword class Student{ int rollno; String name; float fee; Student(int rollno,Stringname,float fee){ this.rollno=rollno; this.name=name; this.fee=fee; } void display(){System.out.println(rollno+" "+name+" "+fee);} } class TestThis2{ public static void main(String args[]){ Student s1=new Student(111,"ankit",5000f); Student s2=new Student(112,"sumit",6000f); s1.display(); s2.display(); }} Output: 111 ankit 5000.0 112 sumit 6000.0 Note:If local variables (formal arguments) and instance variables are different, there is no need to use this keyword. 2. this: to invoke current class method You may invoke the method of the current class by using the this keyword. If you don't use the this keyword, compiler automatically adds this keyword while invoking the method. Let's see the example class A{ void m(){System.out.println("hello m");} void n(){ System.out.println("hello n"); //m();//same as this.m() this.m(); } } class TestThis4{ public static void main(String args[]){ A a=new A(); a.n(); }} Output: hello n hello m 3. this() can be used to invoked current class constructor. The this() constructor call can be used to invoke the current class constructor (constructor chaining). This approach is better if you have many constructors in the class and want to reuse that constructor. class Student{ int id; String name; String city; Student(int id,String name){ this.id = id; this.name = name; } Student(int id,String name,String city){ this(id,name);//now no need to initialize id and name this.city=city; } void display(){System.out.println(id+" "+name+" "+city);} public static void main(String args[]){ Student e1=new Student(111,"karan"); Student e2 =new Student(222,"Aryan","delhi"); e1.display(); e2.display(); }} Output: 111 Karan null 222 Aryan delhi Rule: Call to this() must be the first statement in constructor. Arrays: Normally, an array is a collection of similar type of elements which has contiguous memory location. Java array is an object which contains elements of a similar data type. Additionally, the elements of an array are stored in a contiguous memory location. It is a data structure where we store similar elements. We can store only a fixed set of elements in a Java array. Array in Java is index-based, the first element of the array is stored at the 0th index, and 2nd element is stored on 1st index and so on. Unlike C/C++, we can get the length of the array using the length member. In C/C++, we need to use the sizeof operator. In Java, array is an object of a dynamically generated class. Java array inherits the Object class, and implements the Serializable as well as Cloneable interfaces. We can store primitive values or objects in an array in Java. Like C/C++, we can also create single dimentional or multidimentional arrays in Java. Moreover, Java provides the feature of anonymous arrays which is not available in C/C++. Advantages o Code Optimization: It makes the code optimized, we can retrieve or sort the data efficiently. o Random access: We can get any data located at an index position. Disadvantages o Size Limit: We can store only the fixed size of elements in the array. It doesn't grow its size at runtime. To solve this problem, collection framework is used in Java which grows automatically. Types of Array in java There are two types of array. o Single Dimensional Array o Multidimensional Array Single Dimensional Array in Java Syntax to Declare an Array in Java 1. dataType[] arr; (or) 2. dataType []arr; (or) 3. dataType arr[]; Instantiation of an Array in Java arrayRefVar=new datatype[size]; Example of Java Array Let's see the simple example of java array, where we are going to declare, instantiate, initialize and traverse an array. //Java Program to illustrate how to declare, instantiate, initialize //and traverse the Java array. class Testarray{ public static void main(String args[]){ int a[]; //declaration a=new int; //instantiation a=10; //initialization a=20; a=70; a=40; a=50; int b[]={33,3,4,5,6};//declaration, instantiation and initialization //traversing array for(int i=0;i " + x); //prints modified stack System.out.println("stack: " + stk); } //performing pop operation static void popelmnt(Stack stk) { System.out.print("pop -> "); //invoking pop() method Integer x = (Integer) stk.pop(); System.out.println(x); //prints modified stack System.out.println("stack: " + stk); } } ArrayList Class: Java ArrayList class uses a dynamic array for storing the elements.It extends AbstractList class and implements List interface.  Java ArrayList class can contain duplicate elements.  Java ArrayList class maintains insertion order.  Java ArrayList class is non synchronized. This means that when more than one thread acts simultaneously on the ArrayList object, the results may be incorrect in some cases.  Java ArrayList allows random access because array works at the index basis.  In Java ArrayList class, manipulation is slow because a lot of shifting needs to be occurred if any element is removed from the array list. Constructors of ArrayList Constructor Description ArrayList() It is used to build an empty array list. ArrayList(Collection

Use Quizgecko on...
Browser
Browser