introduction to java sem 5.pdf

Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...

Document Details

ConsiderateEnlightenment7597

Uploaded by ConsiderateEnlightenment7597

Savitribai Phule Pune University

Tags

java programming object-oriented programming software development programming languages

Full Transcript

UNIT 1 INTRODUCTION TO JAVA Introduction to Java 1.1 Features of java 1.2 JDK Environment & tools like (java, javac, appletviewer, javadoc, jdb) 1.3 OOPs Concepts Class, Abstraction, Encapsulation, Inheritance, Polymorphism 1.4 Difference between C++ and JAVA 1.5 Structure of java program 1.6 Data...

UNIT 1 INTRODUCTION TO JAVA Introduction to Java 1.1 Features of java 1.2 JDK Environment & tools like (java, javac, appletviewer, javadoc, jdb) 1.3 OOPs Concepts Class, Abstraction, Encapsulation, Inheritance, Polymorphism 1.4 Difference between C++ and JAVA 1.5 Structure of java program 1.6 Data types, Variables, Operators, Keywords, Naming Convention 1.7 Decision Making (if, switch), Looping (for, while) 1.8 Type Casting 1.9 Array Creating an array Types of Array - One Dimensional arrays - Two-Dimensional array 1.10 String - Arrays, Methods. History Developed by Sun Microsystems in 1995, Java is a highly popular, object-oriented programming language. This platform independent programming language is utilized for Android development, web development, artificial intelligence, cloud applications, and much more. Features of java Simple Object-Oriented Portable Platform independent Secured Robust Architecture neutral Multithreaded Distributed Dynamic Simple Java is very easy to learn, and its syntax is simple, clean and easy to understand. Easy to write and debug programs as Java does not use pointers. Java provides bug-free system due to strong system memory management and also has automatic allocation and deallocation system. Secure Java provides safety and security features. When Java executes a program ,JVM can strictly monitors which makes it great for the Internet applications. Portable An application is developed with help of programming language might be accessed on various computers having different operating system. It is achieved by Bytecode. It is a set of instructions generated by Java compiler while compiling a java program.In java ,a program gets compiled into an intermediate code called bytecode.This bytecode executed by Java Virtual Machine i.e.JVM. Platform independent Java programs can be executed anywhere on any system. Java code can be executed on multiple platforms, for example, Windows, Linux, Sun Solaris, Mac/OS, etc. Java code is compiled by the compiler and converted into bytecode. This bytecode is a platform-independent code because it can be run on multiple platforms, i.e., Write Once and Run Anywhere (WORA). Object-Oriented Java supports Object-oriented programming (OOPs) concepts like Object Class Inheritance Polymorphism Abstraction Encapsulation Robust In java, the problem of memory management is handled by performing automatic garbage collection.It manages memory allocation and deallocation for unused objects. Java also frees programmer from the worries of common causes of programming errors as the program code is verified during compilation. 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. Multithreaded Java is designed for the distributed environment of the Internet using multithreading.This feature helps you write interactive programs, wherein multiple tasks can be performed simultaneously, making it a robust programming language. Distributed Java is distributed as it can be used to create applications to communicate over the network. Java can communicate over the network as it supports TCP/IP.The TCP/IP protocol is a set of network communication protocols. Dynamic During runtime of a Java program, the relevant information that is used to verify & resolve access to objects is required. This concept of providing information is referred to as dynamically linking the code. JDK Environment & tools The development tools for java are provided as a part of the system known as Java Development Kit. Application Programming Interface comprises the classes and interfaces used in Java programming. JDK Java Platforms JVM Java API Java Programs JDK The JDK provides a collection of the Java tools, which are used while developing and running Java programs. java-serves as a Java Interpreter used to run Java applets and applications by reading and interpreting bytecode files. javac -serves as a Java compiler used to translateJava source code to bytecode files. javah-serves as the C header and stub generator, which is used to write native methods. javap-serves as a Java disassemble used to convert bytecode files into a Java program description. jdb:serves as a Java debugger used to find errors in Java programs. appletviewer-facilitates to run Java applets. jar:serves as archive used to package related class libraries into a single executable JAR file and also helps to manage the JAR files. Javadoc:creates HTMl documentation for Java source code files. The Java Programming Language Platforms There are four platforms of the Java programming language: Java Platform, Standard Edition (Java SE) Java Platform, Enterprise Edition (Java EE) Java Platform, Micro Edition (Java ME) Java FX All these Java editions consist of an API (Application Programming Interface) and JVM (Java Virtual Machine). The Java Standard Edition (Java SE) consists of APIs that provide Java's fundamental features, such as security, networking, GUI development, etc. The Java Enterprise Edition (Java EE) was developed to expand the Java SE by adding a collection of specifications that describe frequently used features by commercial applications. The Java Micro Edition (Java ME) was developed to facilitate mobile and embedded device applications. The JavaFX platform uses a simple API to enable the development of rich online applications. Java Standard Edition (Java SE) comprises APIs (Application Programming Interfaces) that provide Java's fundamental programming features. It specifies every aspect of the Java programming language, from its fundamental types and objects to its high-level classes for security, Graphical User Interface development, database manipulation, networking, etc. JVM & Java API The Java Virtual Machine (JVM) tool is used to run Java programs on a certain platform. In java,a compiler translates the Java source code into an intermediate byte code for virtual machine known as JVM. Bytecode is the machine language for JVM and is not machine specific.Instead the machine specific code is generated by the Java Interpreter,which serves as a mediator between virtual machine and real machine. JAVA API It is a collection of classes,interfaces and method in the form of packages which provide many useful capabilities. API packages: java.lang provides classes that are fundamental to the design of the Java Programming language. java.util provides collection classes,event model,collection framework,date and time capabilities,other utility classes as string tokenizer. java.io provides classes for system input and output through data streams ,serialization and the file system. Applet and Network programming packages: java.applet provides classes that are necessary for creating an applet and those which are used to communicate with its applet context. java.net provides classes that are used for implementing networking in java programs Java Programs ◦ Application ◦ Console based ◦ GUI based ◦ Applet OOPs Concepts Object-Oriented Programming is to simplify the design, programming and debugging a program. The main aim of OOP is to bind together the data and the functions that operate on them so that no other part of the code can access this data except that function. The OOP can be defined as an “approach that provides a way of modularizing programs by creating partitioned memory area for both data and functions that can be used as templates for creating copies of such modules on demand.” Concepts of OOP in Java OOPs (Object-Oriented Programming) is a programming paradigm based on the concept of objects, which can contain data in the form of fields (attributes or properties) and code in the form of procedures (methods or functions). In Java, OOPs concepts include encapsulation, inheritance, polymorphism, and abstraction. Java Classes A class in Java is a set of objects which shares common characteristics/ behavior and common properties/ attributes. It is a user-defined blueprint or prototype from which objects are created. For example, Student is a class while a particular student named Ravi is an object. It is just a template or blueprint or prototype from which objects are created. Class does not occupy memory. Class is a group of variables of different data types and a group of methods. A Class in Java can contain: ◦ Data member ◦ Method ◦ Constructor ◦ Nested Class ◦ Interface access_modifier class class_name { data member Method Constructor Nested Class Interface } Java Objects An object in Java is a basic unit of Object-Oriented Programming and represents real-life entities. Objects are the instances of a class that are created to use the attributes and methods of a class. A typical Java program creates many objects, which as you know, interact by invoking methods. Declaring Objects When an object of a class is created, the class is said to be instantiated. All the instances share the attributes and the behavior of the class. But the values of those attributes, i.e. the state are unique for each object. A single class may have any number of instances. Encapsulation Encapsulation in Java is a fundamental concept in object-oriented programming (OOP) that refers to the bundling of data and methods that operate on that data within a single unit, which is called a class in Java. Java Encapsulation is a way of hiding the implementation details of a class from outside access and only exposing a public interface that can be used to interact with the class. Abstraction Hiding internal details and showing functionality is known as abstraction. It refers to the act of representing essential features without including the background details or explanations. Classes use the concept of abstraction and are defined as a list of abstract attributes and methods that operate on these attributes. Inheritance It is the process by which objects of one class acquire the properties of objects of another class. In OOP ,the concept of inheritance provides the idea of reusability. This means that we can add additional features to an existing class without modifying it. This is possible be deriving a new class from the existing one. The new class will have the combined features of both the classes. In Java ,the derived class is known as ‘subclass’. Each subclass defines only those features that are unique to it. POLYMORPHISM It means the ability to take more than one form. Polymorphism allows us to perform a single action in different ways. In other words, polymorphism allows you to define one interface and have multiple implementations. The word “poly” means many and “morphs” means forms, So it means many forms. In Java Polymorphism is mainly divided into two types: Compile-time Polymorphism Runtime Polymorphism Compile-time Polymorphism It is also known as static polymorphism. This type of polymorphism is achieved by function overloading. Method Overloading When there are multiple functions with the same name but different parameters then these functions are said to be overloaded. Functions can be overloaded by changes in the number of arguments or/and a change in the type of arguments. Runtime Polymorphism In Java, Overriding is a feature that allows a subclass or child class to provide a specific implementation of a method that is already provided by one of its super-classes or parent classes. When a method in a subclass has the same name, the same parameters or signature, and the same return type(or sub-type) as a method in its super-class, then the method in the subclass is said to override the method in the super-class. In Java, Access modifiers help to restrict the scope of a class, constructor, variable, method, or data member. It provides security, accessibility etc to the user depending upon the access modifier used with the element. Types of Access Modifiers in Java There are four types of access modifiers available in Java: Default – No keyword required Private Protected Public Default – No keyword required When no access modifier is specified for a class, method, or data member – It is said to be having the default access modifier by default. Private: The private access modifier is specified using the keyword private. The methods or data members declared as private are accessible only within the class in which they are declared. Any other class of the same package will not be able to access these members. Protected: The protected access modifier is specified using the keyword protected. The methods or data members declared as protected are accessible within the same package or subclasses in different packages. Public: The public access modifier is specified using the keyword public. The public access modifier has the widest scope among all other access modifiers. Classes, methods, or data members that are declared as public are accessible from everywhere in the program. There is no restriction on the scope of public data members. Dynamic Binding Binding refers to the linking of a procedure call to the code to be executed in response to the call. Dynamic binding means that the code associated with a given procedure call is not known until the time of the call at runtime. It is associated with polymorphism and inheritance. A procedure call associated with a polymorphic reference depends on the dynamic type of that reference. Message communication An object –oriented program consists of a set of objects that communicate with each other. The process of programming in an object-oriented language, involves the following steps: Creating classes that define objects and their behavior. Creating objects from class definitions Establishing communication among objects. A message for an object is a request for execution of a procedure and Difference Key Points between C++ C++ and Java JAVA In C++, the programmer has to manage the Java supports garbage memory manually with collection. Its memory the use of designated management is operators like delete. automatic. That means Memory management There might be it can automatically free instances where the the memory of the memory is not freed objects that are no which could lead to a longer in use. memory leak problem in C++. Java is platform- independent as the C++ is platform- bytecode created after dependent as its code is compiling the Java code Platform compiled for a targeted can be run on a Java machine. Virtual Machine installed on a machine of any architecture. Structure of java program A Java program typically consists of the following components: Documentation Section Package Declaration Import Statements Interface Section Class Definition Main Method Class Documentation Section Comments are non-executable parts of a program. A compiler does not execute a comment. It is used to improve the readability of the code. Writing comments is a good practice as it improves the documentation of the code. There are three different types of comments- single-line, multi-line, and documentation comments. Single line comment- It is a comment that starts with // and is only used for a single line. Multi line comment- It is a comment that starts with and is used when more than one line has to be enclosed as comments. Documentation comment- It is a comment that starts with Package Declaration Declaring the package in the structure of Java is optional. It comes right after the documentation section. You mention the package name where the class belongs. Only one package statement is allowed in a Java program. EX: package Student; Import Statements Declaring the package in the structure of Java is compulsory. It comes right after the package section. You mention API packages name that you want to use in java program.You can mention more than one built-in package name in a Java program. import java.io.*; import java.util.*; Interface Section This is an optional section. The keyword interface is used to create an interface. An interface contains a set of methods that lack implementation details., i.e. method declaration and constants. interface code { void read(); void write(); } Class Definition This is a mandatory section in the structure of Java program. Each Java program has to be written inside a class. There can be multiple classes in a program. They should begin with an uppercase letter. Ex:class Student { ------------------- -} Main Method Class This is a compulsory part of the structure of Java program. This is the entry point of the compiler where the execution starts. It is called/invoked by the Java Virtual Machine or JVM. The main() method should be defined inside a class. We can call other functions and create objects using this method. The following is the syntax that is used to define. public static void main(String args[]) { } When the main method is declared public, it means that it can also be used by code outside of its class, due to which the main method is declared public. static used when we want to access a method without creating its object, as we call the main method, before creating any class objects. main() is declared as void because it does not return a value. String[] args It is an array where each element of it is a string, which has been named as "args". If your Java program is run through the console, you can pass the input parameter, and main() method takes it as input. Tokens The smallest individuals unit in program are called tokens. Like separators such as (),{},keywords, special characters, operators literals etc. Keywords These words are having standard, predefined, special meaning in Java reserved for their intended purposes.52 keywords. int,float,const,char,long,for,do,while,switch ,class,void,try,catch,finally,throw,throws,package,static,break,bf,boolean Literals A constant value in a program is denoted by a literal. A sequence of characters(digits,letters and other characters) are constant values to be stored in variables. int,float,string,boolen,character literals. Identifiers These are programmer –created tokens. They are used for naming classes,methods,variables,objects,labels,packages&interfaces in a program. Rules for Naming a Variable- A variable may contain characters, digits and underscores. The underscore can be used in between the characters. Variable names should be meaningful. Variable names should not start with a digit or a special character. Data Types Primitive data type ◦ byte ◦ short ◦ int ◦ long ◦ float ◦ double ◦ boolean ◦ char Non Primitive data type ◦ classes ◦ Arrays ◦ interfaces Variables These are reserved memory locations to store values. A variable is a name of location where data is stored when a program executes. Naming conventions: case sensitive Must begin with either a letter or the dollar sign $ or the underscore character ”_”. No white space is permitted in variable names. Do not begin with a digit. Must not be a keyword or reserved word. It can be of any length combination of letters and digits. int num; String name; Operators Operators in Java are the symbols used for performing specific operations in Java. Arithmetic Operators Unary Operators Assignment Operator Relational Operators Logical Operators Ternary Operator Bitwise Operators Shift Operators instance of operator Arithmetic Operators +,-,*,/,% Unary Operators ++,-- Assignment Operator +=,-=,*=,/= Relational Operators ==,!=,>,=, b) ? (a > c) ? a : c : (b > c) ? b : c); Bitwise Operators &, Bitwise AND operator: returns bit by bit AND of input values. |, Bitwise OR operator: returns bit by bit OR of input values. ^, Bitwise XOR operator: returns bit-by-bit XOR of input values. ~, Bitwise Complement Operator: This is a unary operator which returns the one’s complement representation of the input value, i.e., with all bits inverted. Shift Operators > >>> instance of operator is used for type checking. It can be used to test if an object is an instance of a class, a subclass, or an interface. Syntax: object instance of class/subclass/interface Operator Precedence & Associativity If the operators have different precedence, solve the higher precedence first. If they have the same precedence, solve according to associativity, that is, either from right to left or from left to right. Category Operator Associativity Postfix (),[],.(dot operator) Left to Right Unary ++,--,!,~ Right to Left Multiplicative */% Left to Right Addition +- Left to Right Shift ,>>> Left to Right Relational ,=,==,!= Left to Right Bitwise AND & Left to Right Bitwise XOR ^ Left to Right Bitwise OR | Left to Right Logical AND && Left to Right Logical OR || Left to Right Conditional ?: Right to Left Assignment +=,- Right to Left =,*=,%=,>>=,short->int->long->float->double Rules: Two types are compatible. The target type is larger the source type. Explicit casting A data type of higher size can not be assigned to a data type of lower size.It requires explicit casting. The higher size is narrowed to lower size. Double->float->long->int->short->byte import java.io.*; public class test { public static void main(String [] args) { int no1=100; long no2=no1; float no3=no2; System.out.println(“Integer value=“+no1); System.out.println(“Long value=“+no2); System.out.println(“Float value=“+no3); } } Explicit type casting import java.io.*; public class test { public static void main(String [] args) { double no1=1000.234; long no2=(long)no1; int no3=(int)no2; System.out.println(“Double value=“+no1); System.out.println(“Long value=“+no2); System.out.println(“int value=“+no3); } } Arrays An array is a group of contiguous memory locations to store the data of common type. In Java,Arrays may be stored in contiguous memory Since arrays are objects in Java, we can find their length using the object property length. A Java array variable can declared variables with [] after the data type. The variables in the array are ordered, and each has an index beginning with 0. Declaration Single dimensional array type array-name[]; array-name=new type[size]; import java.io.*; class ArrayDemo { public static void main(String args[]) { int a[]={2,4,6,8,10}; System.out.println(“No of array elements in array A”+a.length); System.out.println(“Array elements are”); for (int i=0;i

Use Quizgecko on...
Browser
Browser