JAVA UNIT-I Notes PDF

Summary

These notes cover object-oriented programming (OOP) concepts and Java basics. The document explains OOP paradigms and their use in handling complexity in programming. It details core concepts like abstraction, inheritance, encapsulation, and polymorphism.

Full Transcript

www.android.universityupdates.in | www.universityupdates.in | https://telegram.me/jntuh OBJECT ORIENTED PROGRAMMING THROUGH JAVA UNIT-I Object oriented thinking and Java Basics- Need for oop paradigm, summary of oop c...

www.android.universityupdates.in | www.universityupdates.in | https://telegram.me/jntuh OBJECT ORIENTED PROGRAMMING THROUGH JAVA UNIT-I Object oriented thinking and Java Basics- Need for oop paradigm, summary of oop concepts, coping with complexity, abstraction mechanisms. A way of viewing world – Agents, responsibility, messages, methods, History of Java, Java buzzwords, data types, variables, scope and lifetime of variables, arrays, operators, expressions, control statements, type conversion and casting, simple java program, concepts of classes, objects, constructors, methods, access control, this keyword, garbage collection, overloading methods and constructors, method binding, inheritance, overriding and exceptions, parameter passing, recursion, nested and inner classes, exploring string class. OBJECT ORIENTED THINKING  When computers were first invented, programming was done manually by toggling in a binary machine instructions by use of front panel.  As programs began to grow, high level languages were introduced that gives the programmer more tools to handle complexity.  The first widespread high level language is FORTRAN. Which gave birth to structured programming in 1960’s. The Main problem with the high level language was they have no specific structure and programs becomes larger, the problem of complexity also increases.  So C became the popular structured oriented language to solve all the above problems.  However in SOP, when project reaches certain size its complexity exceeds. So in 1980’s a new way of programming was invented and it was OOP. OOP is a programming methodology that helps to organize complex programs through the use of inheritance, encapsulation & polymorphism. NEED FOR OOP PARADIGM  Traditionally, the structured programming techniques were used earlier.  There were many problems because of the use of structured programming technique.  The structured programming made use of a top-down approach.  To overcome these problems the object oriented programming concept was created.  The object oriented programming makes use of bottom-up approach.  It also manages the increasing complexity.  The description of an object-oriented program can be given as, a data that controls access to code.  The object-oriented programming technique builds a program using the objects along with a set of well-defined interfaces to that object. www.android.previousquestionpapers.com | www.previousquestionpapers.com | https://telegram.me/jntuh www.android.universityupdates.in | www.universityupdates.in | https://telegram.me/jntuh  The object-oriented programming technique is a paradigm, as it describes the way in which elements within a computer program must be organized.  It also describes how those elements should interact with each other.  In OOP, data and the functionality are combined into a single entity called an object.  Classes as well as objects carry specific functionality in order to perform operations and to achieve the desired result.  The data and procedures are loosely coupled in procedural paradigm.  Whereas in OOP paradigm, the data and methods are tightly coupled to form objects.  These objects helps to build structure models of the problem domain and enables to get effective solutions.  OOP uses various principles (or) concepts such as abstraction, inheritance, encapsulation and polymorphism. With the help of abstraction, the implementation is hidden and the functionality is exposed.  Use of inheritance can eliminate redundant code in a program. Encapsulation enables the data and methods to wrap into a single entity. Polymorphism enables the reuse of both code and design. SUMMARY OF OOP CONCEPTS  Everything is an object.  Computation is performed by objects communicating with each other, requesting that other objects perform actions. Objects communicate by sending & receiving messages. A message is a request for an action bundled with whatever arguments may be necessary to complete the task.  Each object has its own memory, which consists of other objects.  Every Object is an instance of class. A class simply represents a grouping of similar objects, such as integers or lists.  The class is the repository for behavior associated with an object. That is all objects that are instances of same class can perform the same actions.  Classes are organized into a singly rooted tree structure, called inheritance hierarchy. www.android.previousquestionpapers.com | www.previousquestionpapers.com | https://telegram.me/jntuh www.android.universityupdates.in | www.universityupdates.in | https://telegram.me/jntuh OOP CONCEPTS OOP stands for Object-Oriented Programming. OOP is a programming paradigm in which every program is follows the concept of object. In other words, OOP is a way of writing programs based on the object concept. The object-oriented programming paradigm has the following core concepts.  Class  Object  Encapsulation  Inheritance  Polymorphism  Abstraction Class Class is a blue print which is containing only list of variables and methods and no memory is allocated for them. A class is a group of objects that has common properties. 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.  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. Encapsulation  Encapsulation is the process of combining data and code into a single unit.  In OOP, every object is associated with its data and code.  In programming, data is defined as variables and code is defined as methods.  The java programming language uses the class concept to implement encapsulation. www.android.previousquestionpapers.com | www.previousquestionpapers.com | https://telegram.me/jntuh www.android.universityupdates.in | www.universityupdates.in | https://telegram.me/jntuh Inheritance  Inheritance is the process of acquiring properties and behaviors from one object to another object or one class to another class.  In inheritance, we derive a new class from the existing class. Here, the new class acquires the properties and behaviors from the existing class.  In the inheritance concept, the class which provides properties is called as parent class and the class which recieves the properties is called as child class. Person name, designation learn(), walk(), eat() Programmer Dancer Singer name, name, name, designation designation designation learn(), learn(), learn(), walk(), walk(), walk(), eat(), eat(), eat(), coding() dancing() singing() Polymorphism  Polymorphism is the process of defining same method with different implementation. That means creating multiple methods with different behaviors.  The java uses method overloading and method overriding to implement polymorphism.  Method overloading - multiple methods with same name but different parameters.  Method overriding - multiple methods with same name and same parameters. Abstraction  Abstraction is hiding the internal details and showing only essential functionality.  In the abstraction concept, we do not show the actual implementation to the end user, instead we provide only essential things.  For example, if we want to drive a car, we does not need to know about the internal functionality like how wheel system works? how brake system works? how music system works? etc. www.android.previousquestionpapers.com | www.previousquestionpapers.com | https://telegram.me/jntuh www.android.universityupdates.in | www.universityupdates.in | https://telegram.me/jntuh COPING WITH COMPLEXITY  Coping with complexity in Java, or any programming language, is an essential skill for software developers.  As your Java projects grow in size and complexity, maintaining, debugging, and extending your code can become challenging. Here are some strategies to help you cope with complexity in Java: 1. Modularization: Breaking down the code into smaller, self-contained modules, classes, or packages to manage complexity. Each module should have a specific responsibility and interact with others through well-defined interfaces. 2. Design Patterns: Using established design patterns to solve common architectural and design problems. Design patterns provide proven solutions to recurring challenges in software development. 3. Encapsulation: Restricting access to class members using access modifiers (public, private, protected) to hide implementation details and provide a clear API for interacting with the class. 4. Abstraction: Creating abstract classes and interfaces to define contracts that classes must adhere to, making it easier to work with different implementations. 5. Documentation: Writing comprehensive documentation, including code comments and Javadoc, to explain how the code works, its purpose, and how to use it. 6. Testing: Implementing unit tests to ensure that individual components of the code function correctly, which helps identify and prevent bugs. 7. Code Reviews: Collaborating with team members to review and provide feedback on code to catch issues and ensure code quality. 8. Version Control: Using version control systems like Git to manage changes, track history, and collaborate with others effectively. 9. Refactoring: Regularly improving and simplifying the codebase by removing redundancy and improving its structure. ABSTRACTION MECHANISM  In Java, abstraction is a fundamental concept in object-oriented programming that allows you to hide complex implementation details while exposing a simplified and well-defined interface.  Abstraction mechanisms in Java include the use of abstract classes and interfaces. www.android.previousquestionpapers.com | www.previousquestionpapers.com | https://telegram.me/jntuh www.android.universityupdates.in | www.universityupdates.in | https://telegram.me/jntuh A WAY OF VIEWING WORLD  A way of viewing the world is an idea to illustrate the object-oriented programming concept with an example of a real-world situation.  Let us consider a situation, I am at my office and I wish to get food to my family members who are at my home from a hotel. Because of the distance from my office to home, there is no possibility of getting food from a hotel myself. So, how do we solve the issue?  To solve the problem, let me call zomato (an agent in food delevery community), tell them the variety and quantity of food and the hotel name from which I wish to delever the food to my family members. AGENTS AND COMMUNITIES Let us consider a situation, I am at my office and I wish to get food to my family members who are at my home from a hotel. Because of the distance from my office to home, there is no possibility of getting food from a hotel myself. So, how do we solve the issue? To solve the problem, let me call zomato (an agent in food delevery community), tell them the variety and quantity of food and the hotel name from which I wish to delever the food to my family members. An object-oriented program is structured as a community of interacting agents, called objects. Where each object provides a service (data and methods) that is used by other members of the community. In our example, the online food delivery system is a community in which the agents are zomato and set of hotels. Each hotel provides a variety of services that can be used by other members like zomato, myself, and my family in the community. RESPONSIBILITIES In object-oriented programming, behaviors of an object described in terms of responsibilities. In our example, my request for action indicates only the desired outcome (food delivered to my family). The agent (zomato) free to use any technique that solves my problem. By discussing a problem in terms of responsibilities increases the level of abstraction. This enables more independence between the objects in solving complex problems. www.android.previousquestionpapers.com | www.previousquestionpapers.com | https://telegram.me/jntuh www.android.universityupdates.in | www.universityupdates.in | https://telegram.me/jntuh MESSAGES & METHODS To solve my problem, I started with a request to the agent zomato, which led to still more requestes among the members of the community until my request has done. Here, the members of a community interact with one another by making requests until the problem has satisfied. In object-oriented programming, every action is initiated by passing a message to an agent (object), which is responsible for the action. The receiver is the object to whom the message was sent. In response to the message, the receiver performs some method to carry out the request. Every message may include any additional information as arguments. In our example, I send a request to zomato with a message that contains food items, the quantity of food, and the hotel details. The receiver uses a method to food get delivered to my home. HISTORY OF JAVA  Java is a object oriented programming language.  Java was created based on C and C++.  Java uses C syntax and many of the object-oriented features are taken from C++.  Before Java was invented there were other languages like COBOL, FORTRAN, C, C++, Small Talk, etc.  These languages had few disadvantages which were corrected in Java.  Java also innovated many new features to solve the fundamental problems which the previous languages could not solve.  Java was developed by James Gosling, Patrick Naughton, Chris warth, Ed Frank and Mike Sheridon at Sun Microsystems in the year 1991.  This language was initially called as “OAK” but was renamed as “Java” in 1995.  The primary motivation behind developing java was the need for creating a platform independent Language (Architecture Neutral), that can be used to create a software which can be embedded in various electronic devices such as remote controls, micro ovens etc.  The problem with C, C++ and most other languages is that, they are designed to compile on specific targeted CPU (i.e. they are platform dependent), but java is platform Independent which can run on a variety of CPU’s under different environments.  The secondary factor that motivated the development of java is to develop the applications that can run on Internet. Using java we can develop the applications which can run on internet i.e. Applet. So java is a platform Independent Language used for developing programs which are platform Independent and can run on internet. www.android.previousquestionpapers.com | www.previousquestionpapers.com | https://telegram.me/jntuh www.android.universityupdates.in | www.universityupdates.in | https://telegram.me/jntuh JAVA BUZZWORDS(JAVA FEATURES)  Java is the most popular object-oriented programming language.  Java has many advanced features, a list of key features is known as Java Buzz Words. The Following list of Buzz Words  Simple  Secure  Portable  Object-oriented  Robust  Architecture-neutral (or) Platform Independent  Multi-threaded  Interpreted  High performance  Distributed  Dynamic Simple  Java programming language is very simple and easy to learn, understand, and code.  Most of the syntaxes in java follow basic programming language C and object-oriented programming concepts are similar to C++.  In a java programming language, many complicated features like pointers, operator overloading, structures, unions, etc. have been removed.  One of the most useful features is the garbage collector it makes java more simple. Secure  Java is said to be more secure programming language because it does not have pointers concept.  java provides a feature "applet" which can be embedded into a web application.  The applet in java does not allow access to other parts of the computer, which keeps away from harmful programs like viruses and unauthorized access. Portable  Portability is one of the core features of java.  If a program yields the same result on every machine, then that program is called portable.  Java programs are portable  This is the result of java System independence nature. Object-oriented  Java is an object oriented programming language.  This means java programs use objects and classes. Robust  Robust means strong.  Java programs are strong and they don’t crash easily like a C or C++ programs www.android.previousquestionpapers.com | www.previousquestionpapers.com | https://telegram.me/jntuh www.android.universityupdates.in | www.universityupdates.in | https://telegram.me/jntuh There are two reasons  Java has got excellent inbuilt exception handling features. An exception is an error that occurs at runtime. If an exception occurs, the program terminates suddenly giving rise to problems like loss of data. Overcoming such problem is called exception handling.  Most of the C and C++ programs crash in the middle because of not allocating sufficient memory or forgetting the memory to be freed in a program. Such problems will not occur in java because the user need not allocate or deallocate the memory in java. Everything will be taken care of by JVM only. Architecture-neutral (or) Platform Independent  Java has invented to archive "write once; run anywhere, anytime, forever".  The java provides JVM (Java Virtual Machine) to archive architectural-neutral or platform- independent.  The JVM allows the java program created using one operating system can be executed on any other operating system. Multi-threaded  Java supports multi-threading programming.  Which allows us to write programs that do multiple operations simultaneously. Interpreted  Java programs are compiled to generate byte code.  This byte code can be downloaded and interpreted by the interpreter in JVM.  If we take any other language, only an interpreter or a compiler is used to execute the program.  But in java, we use both compiler and interpreter for the execution. High performance  The problem with interpreter inside the JVM is that it is slow.  Because of Java programs used to run slow.  To overcome this problem along with the interpreter.  Java soft people have introduced JIT (Just in Time ) compiler, to enhance the speed of execution.  So now in JVM, both interpreter and JIT compiler work together to run the program. Distributed  Information is distributed on various computers on a network.  Using Java, we can write programs, which capture information and distribute it to the client.  This is possible because Java can handle the protocols like TCP/IP and UDP. Dynamic Java is said to be dynamic because the java byte code may be dynamically updated on a running system and it has a dynamic memory allocation and deallocation (objects and garbage collector). www.android.previousquestionpapers.com | www.previousquestionpapers.com | https://telegram.me/jntuh www.android.universityupdates.in | www.universityupdates.in | https://telegram.me/jntuh DATA TYPES IN JAVA Java programming language has a rich set of data types. The data type is a category of data stored in variables. In java, data types are classified into two types and they are as follows.  Primitive Data Types  Non-primitive Data Types Primitive Data Types The primitive data types are built-in data types and they specify the type of value stored in a variable and the memory size. Integer Data Types Integer Data Types represent integer numbers, i.e numbers without any fractional parts or decimal points. Minimum and Maximum Data Type Memory Size Default Value values byte 1 byte -128 to +128 0 short 2 bytes -32768 to +32767 0 int 4 bytes -2147483648 to +2147483647 0 -9223372036854775808 to long 8 bytes 0L +9223372036854775807 www.android.previousquestionpapers.com | www.previousquestionpapers.com | https://telegram.me/jntuh www.android.universityupdates.in | www.universityupdates.in | https://telegram.me/jntuh Float Data Types Float data types are represent numbers with decimal point. Minimum and Maximum Data Type Memory Size Default Value values -3.4e38 to -1.4e-45 and 1.4e-45 float 4 byte 0.0f to 3.4e38 -1.8e308 to -4.9e-324 and 4.9e- double 8 bytes 0.0d 324 to 1.8e308 Note: Float data type can represent up to 7 digits accurately after decimal point. Double data type can represent up to 15 digits accurately after decimal point. Character Data Type Character data type are represents a single character like a, P, &, *,..etc. Minimum and Maximum Data Type Memory Size Default Value values char 2 bytes 0 to 65538 \u0000 Boolean Data Types Boolean data types represent any of the two values, true or false. JVM uses 1 bit to represent a Boolean value internally. Minimum and Maximum Data Type Memory Size Default Value values boolean 1 byte 0 or 1 0 ( false ) www.android.previousquestionpapers.com | www.previousquestionpapers.com | https://telegram.me/jntuh www.android.universityupdates.in | www.universityupdates.in | https://telegram.me/jntuh VARIABLES Variable is a name given to a memory location where we can store different values of the same data type during the program execution. The following are the rules to specify a variable name...  A variable name may contain letters, digits and underscore symbol  Variable name should not start with digit.  Keywords should not be used as variable names.  Variable name should not contain any special symbols except underscore(_).  Variable name can be of any length but compiler considers only the first 31 characters of the variable name. Declaration of Variable Declaration of a variable tells to the compiler to allocate required amount of memory with specified variable name and allows only specified datatype values into that memory location. Syntax: datatype variablename; Example : int a; Syntax : data_type variable_name_1, variable_name_2,...; Example : int a, b; Initialization of a variable: Syntax: datatype variablename = value; Example : int a = 10; Syntax : data_type variable_name_1=value, variable_name_2 = value; Example : int a = 10, b = 20; www.android.previousquestionpapers.com | www.previousquestionpapers.com | https://telegram.me/jntuh www.android.universityupdates.in | www.universityupdates.in | https://telegram.me/jntuh SCOPE AND LIFETIME OF A VARIABLE  In programming, a variable can be declared and defined inside a class, method, or block.  It defines the scope of the variable i.e. the visibility or accessibility of a variable.  Variable declared inside a block or method are not visible to outside.  If we try to do so, we will get a compilation error. Note that the scope of a variable can be nested.  Lifetime of a variable indicates how long the variable stays alive in the memory. TYPES OF VARIABLES IT’S SCOPE There are three types of variables in Java: 1. local variable 2. instance variable 3. static variable Local Variables  Variables declared inside the methods or constructors or blocks are called as local variables.  The scope of local variables is within that particular method or constructor or block in which they have been declared.  Local variables are allocated memory when the method or constructor or block in which they are declared is invoked and memory is released after that particular method or constructor or block is executed.  Access modifiers cannot be assigned to local variables.  It can’t be defined by a static keyword.  Local variables can be accessed directly with their name. www.android.previousquestionpapers.com | www.previousquestionpapers.com | https://telegram.me/jntuh www.android.universityupdates.in | www.universityupdates.in | https://telegram.me/jntuh Program class LocalVariables { public void show() { int a = 10; System.out.println("Inside show method, a = " + a); } public void display() { int b = 20; System.out.println("Inside display method, b = " + b); //System.out.println("Inside display method, a = " + a); // error } public static void main(String args[]) { LocalVariables obj = new LocalVariables(); obj.show(); obj.display(); } } Instance Variables:  Variables declared outside the methods or constructors or blocks but inside the class are called as instance variables.  The scope of instance variables is inside the class and therefore all methods, constructors and blocks can access them.  Instance variables are allocated memory during object creation and memory is released during object destruction. If no object is created, then no memory is allocated.  For each object, a separate copy of instance variable is created.  Heap memory is allocated for storing instance variables.  Access modifiers can be assigned to instance variables.  It is the responsibility of the JVM to assign default value to the instance variables as per the type of  Variable.  Instance variables can be called directly inside the instance area.  Instance variables cannot be called directly inside the static area and necessarily requires an object reference for calling them. www.android.previousquestionpapers.com | www.previousquestionpapers.com | https://telegram.me/jntuh www.android.universityupdates.in | www.universityupdates.in | https://telegram.me/jntuh Program class InstanceVariable { int x = 100; public void show() { System.out.println("Inside show method, x = " + x); x = x + 100; } public void display() { System.out.println("Inside display method, x = " + x); } public static void main(String args[]) { ClassVariables obj = new ClassVariables(); obj.show(); obj.display(); } } Static variables  Static variables are also known as class variable.  Static variables are declared with the keyword ‘static ‘.  A static variable is a variable whose single copy in memory is shared by all the objects, any modification to it will also effect other objects.  Static keyword in java is used for memory management, i.e it saves memory.  Static variables gets memory only once in the class area at the time of class loading.  Static variables can be invoked without the need for creating an instance of a class.  Static variables contain values by default. For integers, the default value is 0. For Booleans, it is false. And for object references, it is null. Syntax: static datatype variable name; Example: static int x=100; Syntax: classname.variablename; www.android.previousquestionpapers.com | www.previousquestionpapers.com | https://telegram.me/jntuh www.android.universityupdates.in | www.universityupdates.in | https://telegram.me/jntuh Example class Employee { static int empid=500; static void emp1() { empid++; System.out.println("Employee id:"+empid); } } class Sample { public static void main(String args[]) { Employee.emp1(); Employee.emp1(); Employee.emp1(); Employee.emp1(); Employee.emp1(); Employee.emp1(); } } ARRAYS  An array is a collection of similar data values with a single name.  An array can also be defined as, a special type of variable that holds multiple values of the same data type at a time.  In java, arrays are objects and they are created dynamically using new operator.  Every array in java is organized using index values.  The index value of an array starts with '0' and ends with 'zise-1'.  We use the index value to access individual elements of an array. In java, there are two types of arrays and they are as follows.  One Dimensional Array  Multi Dimensional Array www.android.previousquestionpapers.com | www.previousquestionpapers.com | https://telegram.me/jntuh www.android.universityupdates.in | www.universityupdates.in | https://telegram.me/jntuh One Dimensional Array In the java programming language, an array must be created using new operator and with a specific size. The size must be an integer value but not a byte, short, or long. We use the following syntax to create an array. Syntax data_type array_name[ ] = new data_type[size]; (or) data_type[ ] array_name = new data_type[size]; Example class Onedarray { public static void main(String args[]) { int a[]=new int; a=10; a=20; a=70; a=40; a=50; for(int i=0;i b)); System.out.println("a < b: " + (a < b)); System.out.println("a >= b: " + (a >= b)); System.out.println("a

Use Quizgecko on...
Browser
Browser