This document provides an overview of Java programming concepts covered in a course. It discusses:
- Sections of the course covering topics like Applets, Multithreading, AWT, Swing, Networking and JDBC.
- A brief history of Java and its versions.
- Core Java concepts like objects, classes, inheritance, interfaces, strings and exceptions.
- Other features like being platform independent, secure, robust and portable.
- Data types, operators, methods, constructors, access modifiers and this keyword in Java.
The document provides an overview of the Java programming language. It discusses that Java was developed in the early 1990s by Sun Microsystems. It then summarizes some of Java's main features, including that it is a simple, object-oriented, robust, distributed, platform independent, secured, architecture-neutral, portable, high-performance, multi-threaded, and dynamic language. It also briefly discusses the Java Virtual Machine, Java Runtime Environment, Java Development Kit, Java bytecode, and the main method.
Java Class 6 | Java Class 6 |Threads in Java| Applets | Swing GUI | JDBC | Ac...Sagar Verma
16. Threads in Java
Non-Threaded Applications
Threaded Applications
Process based multitasking Vs Thread based multitasking
Thread API in Java
Creating Threads
States of a Thread
Synchronization for threads; static and non-static synchronized methods; blocks; concept of object and class locks
Coordination between threads - wait, notify and notifyAll methods for inter-thread communication
17. Applets
What are applets?
Need for Applets
Different ways of running an applet program
Applet API hierarchy
Life Cycle of an applet
Even Handlers for applets, mouse events, click events
18. Swing GUI
Introduction to AWT
Introduction to Swing GUI
Advantages of Swing over AWT
Swing API
Swing GUI Components
Event Handlers for Swing
Sample Calculator application using Swing GUI and Swing Event handling
19. JDBC
What is JDBC; introduction
JDBC features
JDBC Drivers
Setting up a database and creating a schema
Writing JDBC code to connect to DB
CRUD Operations with JDBC
Statement types in JDBC
Types of Rowset, ResultSet in JDBC
20. Access Modifiers in Java
What are access modifiers?
Default
Protected
Private
Public
Core Java introduction | Basics | free course Kernel Training
http://kerneltraining.com/core-java/
Learn the basics of Java and gain practical experience that is required to begin your career in java programming. Kernel Training has designed classroom and online course to upgrade your knowledge and skills in core Java.
Course Curriculum:
Introduction to Java
JDK and practical applications
Java Basic Data Types and Operators
Programming Constructs, Classes and Methods, constructor and Finalizer
Polymorphism
Inheritance
Method overriding and abstract classes
Packages and Interfaces
Strings and Arrays
Enums
The document provides information about Core Java concepts including:
1. James Gosling initiated the Java language project in 1991 and Sun released the first public implementation as Java 1.0 in 1995 with the promise of "Write Once, Run Anywhere".
2. Oracle acquired Sun Microsystems in 2010 and has worked to build fully integrated systems optimized for performance.
3. The document discusses the differences between C++ and Java and covers Java concepts like objects, classes, methods, variables, data types, identifiers, arrays and the Java Virtual Machine (JVM).
Here I discuss about Java programming language and easiest way to solve programming problem. Java basic syntax and their uses are described briefly so that anyone can easily understand within very short time. If anyone follow the slide with proper way,I assure that he or she will find java programming interesting.
This document provides an introduction to Java programming through a series of Java 101 tutorials. It covers setting up a Java development environment with the Java Development Kit and Eclipse IDE. It then introduces Java fundamentals like data types, variables, operators, conditionals, loops, arrays and methods. The tutorials include explanations of concepts and hands-on exercises for writing simple Java programs.
Java was created to address issues with C/C++ by being portable, platform-independent, and secure. It was developed by James Gosling at Sun Microsystems in 1995. Key features of Java include being object-oriented, portable, robust, secure, and having automatic memory management. Java is different from C/C++ in that it does not support pointers, structures, unions, or multiple inheritance.
This document summarizes the key new features included in JDK 7. It discusses Project Coin which added features like string switching, binary literals, and the diamond operator. It also covers try-with-resources for improved exception handling, fork/join framework for parallel programming, and NIO.2 features like asynchronous I/O, watch service for monitoring file changes, and pluggable file systems.
The document provides an overview of the Java programming language. It discusses that Java was developed in the early 1990s by Sun Microsystems. It then summarizes some of Java's main features, including that it is a simple, object-oriented, robust, distributed, platform independent, secured, architecture-neutral, portable, high-performance, multi-threaded, and dynamic language. It also briefly discusses the Java Virtual Machine, Java Runtime Environment, Java Development Kit, Java bytecode, and the main method.
Java Class 6 | Java Class 6 |Threads in Java| Applets | Swing GUI | JDBC | Ac...Sagar Verma
16. Threads in Java
Non-Threaded Applications
Threaded Applications
Process based multitasking Vs Thread based multitasking
Thread API in Java
Creating Threads
States of a Thread
Synchronization for threads; static and non-static synchronized methods; blocks; concept of object and class locks
Coordination between threads - wait, notify and notifyAll methods for inter-thread communication
17. Applets
What are applets?
Need for Applets
Different ways of running an applet program
Applet API hierarchy
Life Cycle of an applet
Even Handlers for applets, mouse events, click events
18. Swing GUI
Introduction to AWT
Introduction to Swing GUI
Advantages of Swing over AWT
Swing API
Swing GUI Components
Event Handlers for Swing
Sample Calculator application using Swing GUI and Swing Event handling
19. JDBC
What is JDBC; introduction
JDBC features
JDBC Drivers
Setting up a database and creating a schema
Writing JDBC code to connect to DB
CRUD Operations with JDBC
Statement types in JDBC
Types of Rowset, ResultSet in JDBC
20. Access Modifiers in Java
What are access modifiers?
Default
Protected
Private
Public
Core Java introduction | Basics | free course Kernel Training
http://kerneltraining.com/core-java/
Learn the basics of Java and gain practical experience that is required to begin your career in java programming. Kernel Training has designed classroom and online course to upgrade your knowledge and skills in core Java.
Course Curriculum:
Introduction to Java
JDK and practical applications
Java Basic Data Types and Operators
Programming Constructs, Classes and Methods, constructor and Finalizer
Polymorphism
Inheritance
Method overriding and abstract classes
Packages and Interfaces
Strings and Arrays
Enums
The document provides information about Core Java concepts including:
1. James Gosling initiated the Java language project in 1991 and Sun released the first public implementation as Java 1.0 in 1995 with the promise of "Write Once, Run Anywhere".
2. Oracle acquired Sun Microsystems in 2010 and has worked to build fully integrated systems optimized for performance.
3. The document discusses the differences between C++ and Java and covers Java concepts like objects, classes, methods, variables, data types, identifiers, arrays and the Java Virtual Machine (JVM).
Here I discuss about Java programming language and easiest way to solve programming problem. Java basic syntax and their uses are described briefly so that anyone can easily understand within very short time. If anyone follow the slide with proper way,I assure that he or she will find java programming interesting.
This document provides an introduction to Java programming through a series of Java 101 tutorials. It covers setting up a Java development environment with the Java Development Kit and Eclipse IDE. It then introduces Java fundamentals like data types, variables, operators, conditionals, loops, arrays and methods. The tutorials include explanations of concepts and hands-on exercises for writing simple Java programs.
Java was created to address issues with C/C++ by being portable, platform-independent, and secure. It was developed by James Gosling at Sun Microsystems in 1995. Key features of Java include being object-oriented, portable, robust, secure, and having automatic memory management. Java is different from C/C++ in that it does not support pointers, structures, unions, or multiple inheritance.
This document summarizes the key new features included in JDK 7. It discusses Project Coin which added features like string switching, binary literals, and the diamond operator. It also covers try-with-resources for improved exception handling, fork/join framework for parallel programming, and NIO.2 features like asynchronous I/O, watch service for monitoring file changes, and pluggable file systems.
Core Java Programming | Data Type | operator | java Control Flow| Class 2Sagar Verma
This document provides an introduction to Java programming concepts including:
- Data types like primitives, classes, and objects
- Variables, identifiers, and naming conventions
- Control structures like if/else statements and loops
- Arrays and array initialization
- Methods and built-in classes
- Import statements and packages
- Output with System.out.println
It covers these concepts over multiple pages with examples and explanations of Java syntax and semantics.
The document discusses key concepts in Java programming including:
1. Java is an object-oriented programming language that is platform independent and allows developers to create applications, applets, and web applications.
2. The Java code is first compiled to bytecode, which can then be executed on any Java Virtual Machine (JVM) regardless of the underlying hardware or operating system.
3. Core Java concepts covered include classes, objects, encapsulation, inheritance, polymorphism, and abstraction. Operators, flow control statements, arrays, strings and object-oriented programming principles are also summarized.
OOPS in java | Super and this Keyword | Memory Management in java | pacakages...Sagar Verma
OOPS and its application in Java, Super class AND This Keyword,Java Bean, POJO ,Memory management in Java ,Packages ,Miscellaneous (Var-Args, toString(), Double equals operator(==))
The document discusses Java packages and classes. It describes common Java API packages like java.lang, java.util, java.io, java.awt, and java.net and what types of classes they contain. It also provides examples of using packages like Vector, Random, Date, and Calendar classes and their key methods. The Calendar class allows interpreting dates and times, defining constants used for components like MONTH, DATE, HOUR, etc.
This document discusses Java class libraries, exceptions, and input/output. It covers the structure of the Java API and how to import classes. It also describes checked and unchecked exceptions, and how to write exception handling code. Finally, it provides examples of reading and writing text and binary files using different stream classes like FileReader, FileWriter, BufferedReader, and BufferedWriter.
This document provides an overview of the Java programming language. It discusses key Java concepts like object-oriented programming, classes, methods, streams, and input/output. It also covers Java syntax like primitive types, variables, operators, flow control, and arrays. The document explains how Java code is compiled to bytecode and run on the Java Virtual Machine, making it platform independent.
The document discusses procedural programming versus object-oriented programming and provides examples using Java. It defines procedural programming as dividing a program into subprocedures that perform specific tasks, with most data shared globally. Object-oriented programming is defined as partitioning memory for both data and functions using objects. The document then outlines key concepts of OOP like objects, classes, encapsulation, and polymorphism. It provides history on the development of Java and its advantages over C++ as a simpler, safer, and more robust language.
This document provides an overview of object-oriented programming concepts in Java. It discusses the differences between procedural and object-oriented programming, with OOP comprising objects that communicate with each other. The main OOP concepts covered are objects, classes, inheritance, and encapsulation. Objects have an identity, attributes, and services. Inheritance allows subclasses to inherit and extend superclass attributes and behaviors. Encapsulation separates an object's internal state from its external interface. The document also discusses other Java topics like interfaces, collections framework, exceptions, and final keywords.
The document discusses object-oriented programming concepts like classes, objects, inheritance, encapsulation, and composition. It provides examples of how these concepts can be implemented in Java. It explains that a class defines common attributes and behaviors of objects, while an object is an instance of a class. Inheritance allows classes to extend and override methods of parent classes. Encapsulation involves making attributes private and accessing them via getter/setter methods. Composition refers to objects having other objects as members.
The document discusses the final keyword in Java and provides examples of using final with variables, methods, and classes. It then summarizes abstract classes and interfaces in Java, including how to declare abstract classes and methods and how interfaces are used to achieve abstraction and multiple inheritance. The document also covers packages, access modifiers, encapsulation, and arrays in Java.
This document provides information about the CS3101-3 Programming Language - JAVA course for Fall 2004. It introduces the instructor, Ke Wang, and his contact information. It states the class will meet on Wednesdays from 11am-1pm for 6 weeks ending on October 20th. There will be 5-6 homework assignments due on Tuesdays at 11:59:59pm. Late submissions are allowed once with a 24-hour extension. The document outlines topics that will be covered in the course like Java basics, objects, classes, inheritance, GUI programming and threads. It provides references to textbooks and online resources.
This document provides a quick reference guide for J2SE (Core Java). It covers various topics related to Java programming including Java history, features, programming structure, data types, control structures, OOP concepts, exceptions, threads, GUI programming and more. The guide was written by A.R. Kishore Kumar and is intended to be a concise yet comprehensive overview of the Java language.
Core Java Tutorial. In case you want to get trained in Spring Framework you can refer here:
<a href="https://www.emexotechnologies.com/courses/java-development-training/core-java-training/">Java Training</a>
The document provides an overview of key Java concepts including classes, objects, variables, methods, encapsulation, inheritance, polymorphism, constructors, memory management, exceptions, I/O streams, threads, collections, serialization and more. It also includes examples of practical applications and code snippets to demonstrate various Java features.
In this cheat sheet, you can find object oriented programming concept's fundamentals very easily. Some topics has very details explanations that could be very helpful those who is in entry level in java mostly object oriented world.
The document provides an overview of core Java basics. It discusses that Java was originally developed by Sun Microsystems and the latest release is Java SE 8. It also explains that Java is object-oriented, platform independent, simple, architecture neutral, portable, robust, multithreaded, interpreted and distributed. The document then discusses Java environment setup, basic syntax including classes, objects and methods. It also covers primitive data types, constructors, OOP concepts like abstraction, encapsulation, inheritance and polymorphism.
This document discusses Java packages and access control. It defines packages as namespaces that group related classes, and describes how to declare packages and import other packages. It then covers the four access modifiers in Java (public, protected, no modifier, private) and their effects on class, package, subclass and other package access. Code examples are provided to demonstrate how to define packages and use different access modifiers to control visibility and accessibility of classes, variables and methods in Java.
This presentation is ideal for a beginner of Java or someone who wants to brush up their Java Knowledge. It's simple to understand and well organized in a way most of the area in core Java has been covered.
The document discusses JPA/Hibernate, object-relational mapping, and web services. It defines Hibernate as an open source ORM for Java that makes data persistent by storing it in a database. It notes that Hibernate automatically generates SQL queries and reduces development time compared to manually handling data with JDBC. The architecture of Hibernate and web services is described, including how Hibernate sits between code and the database to map objects to tables. Common web service types like SOAP and REST are also summarized.
This document provides an introduction to information security (IS). It discusses the history and evolution of IS, from early computer security focusing on physical access to today's landscape where networked computers introduce new threats. The document outlines key IS concepts like the CIA triad and security model, and explains the systems development life cycle approach to implementing a robust IS program within an organization, including roles of various security professionals.
Core Java Programming | Data Type | operator | java Control Flow| Class 2Sagar Verma
This document provides an introduction to Java programming concepts including:
- Data types like primitives, classes, and objects
- Variables, identifiers, and naming conventions
- Control structures like if/else statements and loops
- Arrays and array initialization
- Methods and built-in classes
- Import statements and packages
- Output with System.out.println
It covers these concepts over multiple pages with examples and explanations of Java syntax and semantics.
The document discusses key concepts in Java programming including:
1. Java is an object-oriented programming language that is platform independent and allows developers to create applications, applets, and web applications.
2. The Java code is first compiled to bytecode, which can then be executed on any Java Virtual Machine (JVM) regardless of the underlying hardware or operating system.
3. Core Java concepts covered include classes, objects, encapsulation, inheritance, polymorphism, and abstraction. Operators, flow control statements, arrays, strings and object-oriented programming principles are also summarized.
OOPS in java | Super and this Keyword | Memory Management in java | pacakages...Sagar Verma
OOPS and its application in Java, Super class AND This Keyword,Java Bean, POJO ,Memory management in Java ,Packages ,Miscellaneous (Var-Args, toString(), Double equals operator(==))
The document discusses Java packages and classes. It describes common Java API packages like java.lang, java.util, java.io, java.awt, and java.net and what types of classes they contain. It also provides examples of using packages like Vector, Random, Date, and Calendar classes and their key methods. The Calendar class allows interpreting dates and times, defining constants used for components like MONTH, DATE, HOUR, etc.
This document discusses Java class libraries, exceptions, and input/output. It covers the structure of the Java API and how to import classes. It also describes checked and unchecked exceptions, and how to write exception handling code. Finally, it provides examples of reading and writing text and binary files using different stream classes like FileReader, FileWriter, BufferedReader, and BufferedWriter.
This document provides an overview of the Java programming language. It discusses key Java concepts like object-oriented programming, classes, methods, streams, and input/output. It also covers Java syntax like primitive types, variables, operators, flow control, and arrays. The document explains how Java code is compiled to bytecode and run on the Java Virtual Machine, making it platform independent.
The document discusses procedural programming versus object-oriented programming and provides examples using Java. It defines procedural programming as dividing a program into subprocedures that perform specific tasks, with most data shared globally. Object-oriented programming is defined as partitioning memory for both data and functions using objects. The document then outlines key concepts of OOP like objects, classes, encapsulation, and polymorphism. It provides history on the development of Java and its advantages over C++ as a simpler, safer, and more robust language.
This document provides an overview of object-oriented programming concepts in Java. It discusses the differences between procedural and object-oriented programming, with OOP comprising objects that communicate with each other. The main OOP concepts covered are objects, classes, inheritance, and encapsulation. Objects have an identity, attributes, and services. Inheritance allows subclasses to inherit and extend superclass attributes and behaviors. Encapsulation separates an object's internal state from its external interface. The document also discusses other Java topics like interfaces, collections framework, exceptions, and final keywords.
The document discusses object-oriented programming concepts like classes, objects, inheritance, encapsulation, and composition. It provides examples of how these concepts can be implemented in Java. It explains that a class defines common attributes and behaviors of objects, while an object is an instance of a class. Inheritance allows classes to extend and override methods of parent classes. Encapsulation involves making attributes private and accessing them via getter/setter methods. Composition refers to objects having other objects as members.
The document discusses the final keyword in Java and provides examples of using final with variables, methods, and classes. It then summarizes abstract classes and interfaces in Java, including how to declare abstract classes and methods and how interfaces are used to achieve abstraction and multiple inheritance. The document also covers packages, access modifiers, encapsulation, and arrays in Java.
This document provides information about the CS3101-3 Programming Language - JAVA course for Fall 2004. It introduces the instructor, Ke Wang, and his contact information. It states the class will meet on Wednesdays from 11am-1pm for 6 weeks ending on October 20th. There will be 5-6 homework assignments due on Tuesdays at 11:59:59pm. Late submissions are allowed once with a 24-hour extension. The document outlines topics that will be covered in the course like Java basics, objects, classes, inheritance, GUI programming and threads. It provides references to textbooks and online resources.
This document provides a quick reference guide for J2SE (Core Java). It covers various topics related to Java programming including Java history, features, programming structure, data types, control structures, OOP concepts, exceptions, threads, GUI programming and more. The guide was written by A.R. Kishore Kumar and is intended to be a concise yet comprehensive overview of the Java language.
Core Java Tutorial. In case you want to get trained in Spring Framework you can refer here:
<a href="https://www.emexotechnologies.com/courses/java-development-training/core-java-training/">Java Training</a>
The document provides an overview of key Java concepts including classes, objects, variables, methods, encapsulation, inheritance, polymorphism, constructors, memory management, exceptions, I/O streams, threads, collections, serialization and more. It also includes examples of practical applications and code snippets to demonstrate various Java features.
In this cheat sheet, you can find object oriented programming concept's fundamentals very easily. Some topics has very details explanations that could be very helpful those who is in entry level in java mostly object oriented world.
The document provides an overview of core Java basics. It discusses that Java was originally developed by Sun Microsystems and the latest release is Java SE 8. It also explains that Java is object-oriented, platform independent, simple, architecture neutral, portable, robust, multithreaded, interpreted and distributed. The document then discusses Java environment setup, basic syntax including classes, objects and methods. It also covers primitive data types, constructors, OOP concepts like abstraction, encapsulation, inheritance and polymorphism.
This document discusses Java packages and access control. It defines packages as namespaces that group related classes, and describes how to declare packages and import other packages. It then covers the four access modifiers in Java (public, protected, no modifier, private) and their effects on class, package, subclass and other package access. Code examples are provided to demonstrate how to define packages and use different access modifiers to control visibility and accessibility of classes, variables and methods in Java.
This presentation is ideal for a beginner of Java or someone who wants to brush up their Java Knowledge. It's simple to understand and well organized in a way most of the area in core Java has been covered.
The document discusses JPA/Hibernate, object-relational mapping, and web services. It defines Hibernate as an open source ORM for Java that makes data persistent by storing it in a database. It notes that Hibernate automatically generates SQL queries and reduces development time compared to manually handling data with JDBC. The architecture of Hibernate and web services is described, including how Hibernate sits between code and the database to map objects to tables. Common web service types like SOAP and REST are also summarized.
This document provides an introduction to information security (IS). It discusses the history and evolution of IS, from early computer security focusing on physical access to today's landscape where networked computers introduce new threats. The document outlines key IS concepts like the CIA triad and security model, and explains the systems development life cycle approach to implementing a robust IS program within an organization, including roles of various security professionals.
This document discusses string handling in Java. It begins by explaining that strings are immutable objects of type String. It then discusses why strings are immutable and the security implications if they were mutable. The document also introduces the main string classes in Java and some common string operations like concatenation, comparison, searching and modifying strings. It provides examples for many string methods like length(), charAt(), equals(), indexOf() etc.
String Handling in java
By N.V.Raja Sekhar Reddy
www.technolamp.co.in
Want more interesting...
Watch and Like us @ https://www.facebook.com/Technolamp.co.in
subscribe videos @ http://www.youtube.com/user/nvrajasekhar
The document discusses reactive programming concepts using RxJava. It introduces observables and observers, where observables push asynchronous events to observers via subscriptions. It explains how to create observables that return asynchronous values, and how operators like map, filter, and flatMap can transform and combine observable streams. Key lessons are that performance depends on operator implementations, debugging subscriptions can be difficult, and IDE support for reactive code is still maturing.
This document discusses Java strings and provides information about:
1. What strings are in Java and how they are treated as objects of the String class. Strings are immutable.
2. Two ways to create String objects: using string literals or the new keyword.
3. Important string methods like concatenation, comparison, substring, and length; and string classes like StringBuffer and StringBuilder that allow mutability.
The document provides information on Java OOP concepts including objects, classes, inheritance, polymorphism, abstraction, and encapsulation. It defines objects as entities with state and behavior, and classes as collections of objects. Inheritance allows objects to acquire properties of parent objects. Polymorphism allows one task to be performed in different ways. Abstraction hides internal details and shows functionality, while encapsulation binds code and data together into a single unit.
- Java is an object-oriented programming language originally developed by Sun Microsystems that is both compiled and interpreted. Source code is compiled into bytecode, which is then run by the Java Virtual Machine (JVM) on any platform.
- Key features of Java include platform independence, security through sandboxing of applications, dynamic class loading, and versions for different uses including Java Micro Edition for small devices and Java Enterprise Edition for business applications.
- A Java program consists of classes that describe objects. Classes contain data fields and methods, and can extend existing classes. Commonly used classes are organized into packages.
The document discusses Java strings and string comparison. It provides details on Java string class methods like charAt(), length(), substring(), contains(), equals(), etc. It also discusses the three ways to compare strings in Java: 1) Using the equals() method which compares string content, 2) Using the == operator which compares references, and 3) Using the compareTo() method which compares strings lexicographically. Examples of comparing strings using the equals() method are also provided.
The document provides information about File classes and Input/Output streams in Java. It discusses the File class which represents file and directory pathnames and allows creating, deleting, and renaming files. It also describes InputStream and OutputStream classes used for reading bytes from and writing bytes to streams. Examples are given of using FileInputStream to read from a file and FileOutputStream to write to a file. The document also discusses RandomAccessFile for random access of files and JDBC for connecting to databases.
Java ppt Gandhi Ravi (gandhiri@gmail.com)Gandhi Ravi
This document provides an introduction to the Java programming language. It discusses that Java is an object-oriented, platform-independent language that uses a runtime environment and API. It explains how Java code is compiled and executed. It also covers Java applications, data types, operators, keywords, variables, constructors, inheritance, polymorphism, arrays and other core Java concepts. The document provides examples to illustrate different Java programming concepts.
This document provides an overview of Java basics including where Java is used, its key features, object-oriented programming concepts, platform independence, the structure of a basic Java program, variable types, operators, naming conventions, and constructors. Java is commonly used in desktop applications, web applications, enterprise applications, mobile apps, embedded systems, and more. It is a simple, secure, robust, portable, and interpreted language that is object-oriented, platform independent and supports multithreading. The document defines classes, inheritance, polymorphism, abstraction, and encapsulation. It also explains Java data types, variables, operators, and naming conventions. Constructors are special methods used to initialize objects that are invoked during object creation.
Introduction of Object Oriented Programming Language using Java. .pptxPoonam60376
The slide contains the Introduction of Object Oriented Programming Language using Java. It covers basics of OOP, Inheritance,Polymorphism, Exception etc.
This document provides an overview of object-oriented programming concepts in Java including classes, objects, attributes, methods, constructors, access modifiers, packages, and encapsulation. It defines these concepts, provides examples of how to declare and use them, and explains how they help achieve information hiding and modularity through features like abstraction, encapsulation, and packages.
The document provides information about object-oriented programming concepts in Java including objects, classes, constructors, and access modifiers. It defines an object as having state, behavior, and identity. A class is described as a template or blueprint for creating objects that share common properties. The document discusses default and parameterized constructors. It also covers the static keyword in relation to variables, methods, blocks, and nested classes. Other topics include finalizer methods, import statements, and the four levels of access control in Java.
This document discusses the syllabus for the course IT1301 - Object Oriented Programming. It covers key concepts in OOP like classes, objects, inheritance, polymorphism, abstraction and encapsulation. It also discusses features of Java like being platform independent, secure, robust etc. The document contains examples and questions related to OOP concepts in Java. Constructors and their types, access specifiers, object class and reflection are explained in detail with examples. Creation and accessing of user-defined packages in Java is also discussed.
The document appears to be a laboratory manual for a Java programming lab course. It includes:
1) An outline of the course syllabus, marks scheme, and lab plan covering topics like classes and objects, inheritance, exceptions, files and more across 10 lab turns.
2) Objectives of the lab to develop understanding of Java concepts like OOPs, packages, strings, files and concurrency.
3) Examples of basic Java programs to print text, calculate area, check prime numbers and generate a number ladder.
This document provides an overview of Java including its history, versions, key features, and basic programming concepts. It describes how Java was originally called Oak and later renamed to Java in 1995. It also lists the main Java versions from 1995 to 2011. Additionally, it defines Java as a platform independent language and outlines some of its common uses. The document proceeds to explain Java's main features such as being simple, object-oriented, platform independent, secure, portable, dynamic, high performance, and multithreaded. It also includes examples of a simple Java program, variables, and packages.
Java is an object-oriented programming language that is derived from C and C++. It can be used to create a variety of applications including standalone applications, web applications, enterprise applications, and mobile applications. Java programs are compiled to bytecode that can run on any Java Virtual Machine, making Java platform independent. Key features of Java include being simple, object-oriented, platform independent, secure, robust, and multi-threaded. The basic structure of a Java program includes classes that contain methods. Methods can be overloaded by changing their parameters.
JAVA - A Quick Reference
A quick guide to learn more about JAVA Programming. This covers the core concepts of JAVA with OOP concepts. This also covers swing programming.
This document discusses classes, methods, objects, constructors and other object-oriented programming concepts in Java. Some key points:
- Classes are templates that define objects, while objects are instances of classes that have state and behavior.
- Methods are collections of code that perform specific tasks and provide reusability. The main() method is important as it is executed first.
- Constructors initialize objects and are automatically called when objects are created. There can be default and parameterized constructors.
- Objects are created using the new keyword and access class members like methods using the dot operator. Arrays can store multiple objects.
- Methods and constructors can be overloaded when they have the same name but different parameters
oops concept in java | object oriented programming in javaCPD INDIA
The document discusses key concepts in object-oriented programming in Java including classes, objects, inheritance, packages, interfaces, encapsulation, abstraction, and polymorphism. It provides examples to illustrate each concept. Classes define the structure and behavior of objects. Objects are instances of classes. Inheritance allows classes to extend existing classes. Packages organize related classes. Interfaces define behaviors without implementation. Encapsulation hides implementation details. Abstraction models essential features without specifics. Polymorphism allows the same method name with different signatures or overriding.
- Java uses a bytecode format instead of machine code and disallows pointer arithmetic, improving security. Pointer support is not used in Java because it would require expensive runtime checks to ensure safe memory access.
- The Java execution process involves class loading, bytecode verification, interpretation/compilation, and execution. The class loader loads .class files.
- The JDK contains development tools, the JRE contains libraries and other files used at runtime including the JVM specification. The JVM is an abstract machine that executes Java bytecode.
This document provides an overview of object-oriented programming fundamentals in Java, including basic concepts like objects, classes, inheritance, polymorphism, and encapsulation. It discusses Java features, the Java program structure, variables and data types, operators, expressions, arrays, and control statements. Object-oriented programming concepts like abstraction, encapsulation, inheritance and polymorphism are explained. The benefits and applications of OOP are also highlighted.
Java programing language unit 1 introductionchnrketan
This document provides an overview of key Java concepts including:
- Java is a popular, platform-independent object-oriented programming language.
- Key Java features include being object-oriented, having automatic memory management, and using a virtual machine.
- Core Java topics covered include arrays, strings, classes, objects, methods, and exceptions.
1. Programming in java
Section-I
1. Introduction (6 hrs)
2. Applet as java application (2 hrs)
3. Multithreaded programming (4 hrs)
4. AWT and Java Input Output (8 hrs)
Section-II
1. Introduction to Swing (5 hrs)
2. Networking with Java (5 hrs)
3. JDBC (6 hrs)
4. RMI (4 hrs)
2. 1. Introduction
Brief history of Java
Java Version History
Features of Java
Objects and classes
Inheritance
Abstract classes
Interface
Use of final Keyword
Use of String functions
Packages
Exception handling
3. Brief history of Java
History of java starts from Green Team
James Gosling, Mike Sheridan, and Patrick Naughton Green
Team initiated the Java language project in June 1991
Originally designed for small, embedded systems in
electronic appliances
Earlier it was called Oak and developed as a part of the
Green project
Oak is a symbol of strength and choosen as a national tree
of many countries like U.S.A
In 1995, Oak was renamed as "Java" because it was already
a trademark by Oak Technologies
4. Why Java name for java language?
Java is an island of Indonesia where first coffee was
produced (called java coffee)
Java is just a name not an acronym
Originally developed by James Gosling at Sun
Microsystems and released in 1995.
JDK 1.0 released in (January 23, 1996)
<BACK>
5. Java Version History
Java versions:
1. JDK Alpha and Beta (1995)
2. JDK 1.0 (1996)
3. JDK 1.1 (1997)
4. J2SE 1.2 (1998)
5. J2SE 1.3 (2000)
6. J2SE 1.4 (2002)
7. J2SE 5.0 (2004)
8. Java SE 6 (2006)
9. Java SE 7 (2011)
10. Java SE 8 (18th March, 2014) Current stable release
of Java
7. 1. Syntax is based on C++
2. Removed many confusing features e.g. explicit
pointers, operator overloading etc
3. Automatic Garbage Collection in java
Simple
8. Object-Oriented
Object-oriented means organize software as combination of
different types of objects that incorporate both data and
behavior
Basic concepts of OOPs are:
Object
Class
Inheritance
Polymorphism
Abstraction
Encapsulation
9. Platform independent
A platform is hardware or software environment in which a
program runs
Java provides software-based platform
Runtime Environment
API(Application Programming Interface)
Java code is compiled by the compiler and converted into
bytecode.
Bytecode is a platform independent code because it can be run
on multiple platforms i.e. Write Once and Run
Anywhere(WORA).
11. Java is secured because :
No explicit pointer
Programs run inside virtual machine sandbox
Secured
12. 1. Robust means strong.
2. Java uses strong memory management.
3. Lack of pointers that avoids security problem.
4. Automatic garbage collection.
5. Exception handling and type checking mechanism.
All these makes java robust.
No implementation dependent features e.g. size of primitive
types is set
Architecture neutral
Robust
13. Portable
Allow to carry the java bytecode to any platform
Dynamic
Java is capable of dynamically linking new class libraries,
methods and objects.
Determines the class through query, making possible to link
dynamically
14. Interpreted
Java interpreter generates machine code that can be directly by
the machine with the help of JVM
High Performance
Java is faster than traditional interpretation since byte code is
"close" to native code still somewhat slower than a compiled
language (e.g., C++)
15. Multithreaded
Java allow to handle multiple tasks simultaneously. Java supports
multithreaded programs
Distributed
We can create distributed applications in java.
RMI and EJB are used for creating distributed applications.
We may access files by calling the methods from any machine
on the internet
<BACK>
16. Data Types in Java
1. Primitive data types
2. Non-primitive data types
17. Data Type Default Value Default size
boolean false 1 bit
char 'u0000' 2 byte
byte 0 1 byte
short 0 2 byte
int 0 4 byte
long 0L 8 byte
float 0.0f 4 byte
double 0.0d 8 byte
18. Operators in java
Operator is a symbol that is used to perform operations.
Operators Precedence
postfix expr++ expr--
unary ++expr --expr +expr -expr ~ !
multiplicative * / %
additive + -
shift << >> >>>
relational < > <= >= instanceof
equality == !=
bitwise AND &
bitwise exclusive OR ^
bitwise inclusive OR |
logical AND &&
logical OR ||
ternary ? :
assignment = += -= *= /= %= &= ^= |= <<= >>=>>>=
19. Objects and classes
Object in Java
An entity that has state and behavior is known as an object.
It can be physical or logical.
Object is an instance of a class.
Instance variable in Java
A variable that is created inside the class but outside the
method, is known as instance variable. Instance variable
doesn't get memory at compile time.
20. State: Represents data (value) of an object.
Behavior: Represents the behavior (functionality) of an
object e.g. deposit, withdraw etc.
Identity: Object identity is a unique ID. JVM use ID to
identify each object uniquely
Object Properties
21. Class in Java
Class is a template or blueprint from which objects are created.
A class is a group of objects that has common properties
A class contains :
1. Data member
2. Method
3. Constructor
4. Block
5. Class and interface
22. Syntax to declare a class:
class <class_name>
{
data member;
method;
}
23. Example of Object and Class
class Student {
int id; String name; //data member (also instance variable)
public static void main(String args[])
{ Student s1 = new Student(); //creating an object of Student
System.out.println(s1.id);
System.out.println(s1.name);
}
}
24. class Student {
int rollno;
String name;
void insertRecord (int r, String n) { rollno = r; name = n; }
void displayRecord() {System.out.println(rollno+" "+name);}
public static void main(String args[]){
Student s1 = new Student();
Student s2 = new Student();
s1.insertRecord(111,"Amit");
s2.insertRecord(222,"Ajay");
s1.displayRecord ();
s2.displayRecord ();
}
}
<BACK>
25. class Rectangle {
int length; int width;
void insert(int l,int w) { length=l; width=w; }
void calculateArea() { System.out.println(length*width); }
public static void main(String args[]) {
Rectangle r1 = new Rectangle();
Rectangle r2 = new Rectangle();
r1.insert(11,5); r2.insert(3,15);
r1.calculateArea(); r2.calculateArea();
}
}
26. Method Overloading in Java
If a class have multiple methods with same name but different
parameters, it is known as Method Overloading.
Different ways to overload the method
1. By changing the no. of arguments
2. By changing the data type
Method overloading increases the readability of the program.
Can we overload the main method?
27. Method Overloading by changing the no. of arguments
class Myclass{
void sum(int a, int b) { System.out.println(a+b);}
void sum(int a, int b, int c) { System.out.println(a+b+c); }
public static void main(String args[]) {
Myclass obj =new Myclass();
obj.sum(10, 10, 10);
obj.sum(20, 20);
}
}
28. Method Overloading by changing data type of an argument
class Myclass{
void sum(int a, int b) { System.out.println(a+b); }
void sum(double a, double b) { System.out.println(a+b); }
public static void main(String args[]) {
Myclass obj = new Myclass();
obj.sum(10.5, 10.5);
obj.sum(20, 20);
}
}
29. Method Overloading and Type Promotion
One type is promoted to another implicitly if no matching
data type is found as in figure given below;
As displayed in the diagram, byte can be promoted to
short, int, long, float or double.
30. Method Overloading and Type Promotion (cont…)
class Myclass {
void sum(int a, long b) { System.out.println(a+b); }
void sum(int a, int b, int c) { System.out.println(a+b+c); }
public static void main(String args[]) {
Myclass obj =new Myclass();
obj.sum(20, 20); //now second int literal will be promoted to long
obj.sum(20, 20, 20);
}
}
Output: 40
60
31. Constructor in Java
Types of constructors
1. Default Constructor
2. Parameterized Constructor
Constructor Overloading
Does constructor return any value
Does constructor perform other task instead initialization
Rules to define the constructor
1. Constructor name must be same as its class name
2. Constructor must have no explicit return type
Constructor is a special type of method that is used to
initialize the object
32. Default Constructor
A constructor that has no parameter is known as default
constructor.
Syntax of default constructor:
<class_name>() { }
Example of default constructor
class Bike {
Bike() {System.out.println("Bike is created");}
public static void main(String args[])
{ Bike b=new Bike(); }
}
Output: Bike is created
33. Parameterized constructor
A constructor that has parameters is known as parameterized
constructor
Example of parameterized constructor
class Student {
int id; String name;
Student(int i, String n) { id = i; name = n; }
void display() {System.out.println(id+" "+name);}
public static void main(String args[]) {
Student s1 = new Student(111,“Vijay");
Student s2 = new Student(222,“Ajay");
s1.display(); s2.display();
}
Output: 111 Vijay 222 Ajay
34. No copy constructor in java
We can copy the values of one object to another like copy
constructor in C++.
Ways to copy the values of one object into another in java.
1. By constructor
2. By assigning the values of one object into another
35. Copy the values of one object into another using constructor
class Student {
int id; String name;
Student(int i,String n) { id = i; name = n; }
Student(Student s) { id = s.id; name =s.name; }
void display() {System.out.println(id+" "+name); }
public static void main(String args[]) {
Student s1 = new Student(111,"Karan");
Student s2 = new Student(s1);
s1.display(); s2.display();
} }
Output: 111 Karan
111 Karan
36. Copying values without constructor
class Student {
int id; String name;
Student(int i,String n) { id = i; name = n; }
Student(Student s) { id = s.id; name =s.name; }
void display() {System.out.println(id+" "+name);}
public static void main(String args[]) {
Student s1 = new Student(111,"Karan");
Student s2 = new Student();
s2.id = s1.id; s2.name = s1.name;
s1.display(); s2.display();
} }
Output: 111 Karan 111 Karan
37. Constructor Overloading
Constructor overloading is a technique in which a class can
have any number of constructors that differ in parameter lists.
class Student {
int id; String name; int age;
Student(int i, String n) { id = i; name = n; }
Student(int i, String n, int a) { id = i; name = n; age=a; }
void display(){System.out.println(id+" "+name+" "+age);}
public static void main(String args[]) {
Student s1 = new Student(111,“Ajay");
Student s2 = new Student(222,“Vijay",25);
s1.display(); s2.display(); }
}
Output: 111 Ajay 0 222 Vijay 25
38. static keyword
1. The static keyword is used for memory management
mainly.
2. We can apply static keyword with variables, methods,
blocks and nested class.
3. The static keyword belongs to the class than instance of the
class.
The static keyword can be used with:
1. class variable
2. class method
39. static variable and method
1. The static variable can be used to refer the common property of all
objects.
2. The static variable gets memory only once in class area at the time of
class loading.
Example of static variable
1. class Student {
2. int rollno; String name;
3. static String college =“sscs";
4. Student(int r, String n) { rollno = r; name = n; }
5. void display () {System.out.println(rollno+" "+name+" "+college); }
6. public static void main(String args[]){
7. Student s1 = new Student(111, “Vijay");
8. Student s2 = new Student(222, “Ajay");
9. s1.display(); s2.display();
10. } }
40. this keyword
Usages of this keyword.
1. to refer current class instance variable.
2. to return the current class instance.
3. to invoke current class method (implicitly)
4. this can be used to invoked current class constructor
5. can be passed as an argument in the method call
If there is ambiguity between the instance variable and
parameter, this keyword resolves the problem of ambiguity
41. 1. class Student{
2. int id; String name;
3. Student(int id, String name){
4. this.id = id; this.name = name;
5. }
6. void display(){System.out.println(id+" "+name);}
7. public static void main(String args[]){
8. Student s1 = new Student(111,“Vijay");
9. Student s2 = new Student(222,“Ajay");
10. s1.display();
11. s2.display();
12. }
13. }
Output: 111 Vijay
222 Ajay
Refer current class instance variable
42. Program of this() constructor call (constructor chaining)
1. class Student {
2. int id; String name;
3. Student() {System.out.println("default constructor is invoked");}
4. Student(int id, String name) {
5. this (); //it is used to invoked current class constructor.
6. this.id = id; this.name = name;
7. }
8. void display() {System.out.println(id+" "+name);}
9. public static void main(String args[]){
10. Student e1 = new Student(111,“Vijay");
11. Student e2 = new Student(222,“Ajay");
12. e1.display(); e2.display();
13. } }
Output: default constructor is invoked
default constructor is invoked
111 Vijay 222 Ajay
43. 1. class Student {
2. int id; String name; String city;
3. Student(int id,String name) {
4. this.id = id; this.name = name;
5. }
6. Student(int id, String name, String city) {
7. this(id, name); //now no need to initialize id and name
8. this.city=city;
9. }
10. void display() {System.out.println(id+" "+name+" "+city);}
11. public static void main(String args[])
{ Student e1 = new Student(111,"karan");
12. Student e2 = new Student(222,"Aryan","delhi");
13. e1.display();
14. e2.display(); }
15. }
Invoke current class constructor
44. this use to invoke current class method
1. class S {
2. void m() { System.out.println("method is invoked"); }
3. void n() { this.m(); //no need because compiler does it for you. }
4. void p() { n(); }
//complier will add this to invoke n() method as this.n()
5. public static void main(String args[])
6. { S s1 = new S();
7. s1.p();
8. }
9. }
45. this pass as an argument in the method
1. class S {
2. void m (S obj) { System.out.println("method is invoked"); }
3. void p(){ m(this); }
4. public static void main(String args[]){
5. S s1 = new S();
6. s1.p();
7. }
8. }
Output:method is invoked
46. this use to return current class instance
1. class A {
2. A getA() { return this; }
3. void msg() {System.out.println("Hello java");}
4. }
5.
6. class Test1 {
7. public static void main(String args[]) {
8. new A().getA().msg();
9. }
10. }
47. Program of counter by static variable
1. class Counter{
2. static int count=0;
//will get memory only once and retain its value
3. Counter () {
4. count++;
5. System.out.println(count); }
6. public static void main(String args[]){
7. Counter c1=new Counter2();
8. Counter c2=new Counter2();
9. Counter c3=new Counter2();
10. }
11. }
Output:1 2 3
48. static method
static keyword with any method, it is known as static method.
1. A static method belongs to the class rather than object of a class.
2. A static method can be invoked without creating an instance of a class.
3. A static method can access static data member and can change the value
•class Student {
• int rollno; String name; static String college = "ITS";
• static void change() { college = "BBDIT"; }
• Student(int r, String n) { rollno = r; name = n; }
• void display (){System.out.println(rollno+" "+name+" "+college);}
• public static void main(String args[]){
• Student.change();
• Student s1 = new Student (111,"Karan");
• Student s2 = new Student (222,"Aryan");
• Student s3 = new Student (333,"Sonoo");
• s1.display(); s2.display(); s3.display();
• } }
Output: 111 Karan BBDIT 222 Aryan BBDIT 333 Sonoo BBDIT
49. Restrictions for the static method
The static method can not use non static data member or call
non-static method directly.
this and super cannot be used in static context.
Restrictions for static method
1. class A {
2. int a=40;//non static
3.
4. public static void main(String args[]){
5. System.out.println(a);
6. }
Output:Compile Time Error
50. static block
1. Is used to initialize the static data member.
2. It is executed before main method at the time of class
loading.
3. class A {
4. static{System.out.println("static block is invoked");}
5. public static void main(String args[]){
6. System.out.println("Hello main");
7. }
8. }
Output: static block is invoked
Hello main
51. Inheritance
Inheritance is a process in which one object acquires all properties
and behaviors of parent object.
When we inherit from an existing class, we can reuse methods and
fields of parent class, and add new methods and fields.
Inheritance represents the IS-A relationship or parent-child
relationship.
Inheritance allow :
Method Overriding
Code Reusability
<BACK>
52. Syntax of Inheritance
class Subclass-name extends Super class-name
{ //methods and fields }
The extends keyword indicates that we are making a new class that derives
from an existing class.
Relationship between two classes is Programmer IS-A Employee e.g.
Programmer is a type of Employee.
1. class Employee { float salary=50000; }
2. class Programmer extends Employee {
3. int bonus=10000;
4. public static void main(String args[]){
5. Programmer p=new Programmer();
6. System.out.println("Programmer salary is:"+p.salary);
7. System.out.println("Bonus of Programmer is:"+p.bonus
8. } }
53. Types of inheritance
There are three types of inheritance as :
1. Single
2. Multilevel and
3. Hierarchical
Multiple and hybrid inheritance is not supported through interface.
To reduce the complexity and simplify the language, multiple inheritance is
not supported in java.
54. Consider A, B and C are three classes. The C class inherits A and
B classes. If A and B classes have same method and we call it
from child class object.
class A { void msg() { System.out.println("Hello"); } }
class B { void msg() { System.out.println("Welcome");} }
class C extends A, B {
public Static void main(String args[]) {
C obj = new C();
obj.msg(); //Now which msg() method would be invoked?
}
}
<BACK>
55. Aggregation
If a class have an entity reference, it is known as Aggregation.
Aggregation represents HAS-A relationship.
Consider an Employee object contains information as id, name,
email id etc. It contains other object address, which contains
information as city, state, country, zip code etc. as below.
class Employee{
int id; String name;
Address address;//Address is a class
...
}
Aggregation is for Code Reusability.
56. Example of Aggregation
public class Address { String city, state, country;
public Address (String city, String state, String country) {
this.city = city; this.state = state; this.country = country; } }
public class Emp { int id; String name; Address address;
public Emp(int id, String name, Address address) {
this.id = id; this.name = name; this.address=address; }
void display() { System.out.println (id+" "+name);
System.out.println(address.city+" "+address.state+" "+address.country); }
public static void main(String[] args) {
Address address1 = new Address(“abc",“Sol","india");
Address address2 = new Address(“lmn",“Sol","india");
Emp e1 = new Emp(111, “Vijay", Solapur);
Emp e2 = new Emp(112, “Ajay", Pandharpur);
e1.display(); e2.display(); }
}
57. Method Overriding
Subclass (child class) has the same method as declared in the
parent class, it is known as method overriding.
Usage of Method Overriding
1. To provide specific implementation of a method that is
already provided by its super class.
2. For runtime polymorphism
Rules for Method Overriding
1. method must have same name as in the parent class
2. method must have same parameter as in the parent
class.
3. must be IS-A relationship (inheritance).
58. Example of method overriding
1. class Vehicle{
2. void run() { System.out.println("Vehicle runs"); }
3. }
4. class Bike extends Vehicle{
5. void run() { System.out.println(“Runs safely"); }
6.
7. public static void main(String args[]){
8. Bike obj = new Bike();
9. obj.run();
10. }
59. Difference between method Overloading and Overriding
Method Overloading Method Overriding
Used to increase the
readability of the program
Used to provide the specific
implementation of the method that is
already provided by its super class
Performed within a class. Occurs in two classes that have IS-A
relationship
In method overloading,
parameter must be different
In method overriding, parameter must be
same
60. super keyword
super keyword is a reference variable that is used to refer immediate
parent class object.
When we create the instance of subclass, an instance of parent class
is created implicitly i.e. referred by super reference variable
Usage of super Keyword
1. To refer immediate parent class instance variable
2. To invoke immediate parent class constructor
3. To invoke immediate parent class method
61. Example to use super():
1. class Vehicle {
2. Vehicle() { System.out.println("Vehicle is created");
3. myvehicle() { System.out.println(“My car”); }
4. }
5. class Bike extends Vehicle {
6. Bike() { super(); //will invoke parent class constructor
7. System.out.println("Bike is created"); }
8. public static void main(String args[]) {
9. Bike b=new Bike(); super.myvehicle(); }
10. }
Output: Vehicle is created Bike is created
My car
62. Use of final keyword
The final keyword is used to restrict the user. The final keyword can be
used in many case.
Final can be used with :
1. variable
2. method
3. Class
Is final method inherited ?
Can you declare a final constructor?
63. final variable
If we make any variable as final, we cannot change the value of
final variable.
Example:
1. class Bike {
2. final int speedlimit=90; //final variable
3. void run() { speedlimit=400; }
4. public static void main(String args[]) {
5. Bike obj = new Bike();
6. obj.run(); }
7. } //end of class
Output: Compile Time Error
64. final method
If we make any method as final, we cannot override it.
Example:
class Bike { final void run() { S.o.p("running");} }
class Honda extends Bike {
void run() { ystem.out.println(“Runs safely with 100kmph"); }
public static void main(String args[]) {
Honda hunk = new Honda();
hunk.run(); }
}
Output: Compile Time Error
65. final class
If we make class as final, we cannot extend it.
Example:
1. final class Bike {}
2. class Honda extends Bike {
3. void run()
4. { System.out.println("running safely with 100kmph"); }
5. public static void main(String args[]) {
6. Honda hunk= new Honda();
7. hunk.run();
8. }
9. }
Output: Compile Time Error
Is final method inherited? Yes, final method is inherited but can’t override.
66. Final parameter
If we declare any parameter as final, we can’t change the value of it.
1. class Bike {
2. int cube( final int n) {
3. n=n+2; //can't be changed as n is final
4. n*n*n; }
5. public static void main(String args[]) {
6. Bike b = new Bike();
7. b.cube(5);
8. }
9. }
Output: Compile Time Error
<BACK>
67. Abstract class
Abstraction is a process of hiding implementation details and showing
only functionality.
It shows only important things and hides the internal details.
e.g. sending sms
Abstraction focus on what the object does instead of how it does it.
Abstract class
A class that is declared with abstract keyword, is known as abstract class.
It can have abstract and non-abstract methods (method with body).
68. Abstract class example:
abstract class A { … }
Abstract method
A method that is declared as abstract and does not have implementation
(body) is known as abstract method.
Abstract method example:
abstract void print(); //no implementation and is abstract
Program Example:
1. abstract class Bike { abstract void run(); }
2. class Honda extends Bike {
3. void run() {System.out.println("running safely..");}
4. public static void main(String args[]) {
5. Bike obj = new Honda4(); obj.run(); }
6. }
Output put : running safely..
69. Interface in Java
An interface is a frame of a class. It has static constants and abstract
methods only. Interface represents IS-A relationship.
Reasons to use interface:
1. To achieve fully abstraction.
2. Support the multiple inheritance.
3. Achieve loose coupling.
Interface data members are public,
static and final by default.
Methods are public and abstract.
70. A class extends another class, an interface extends another
interface but a class implements an interface
71. ‘Printable’ interface have only one method, its implementation is
provided in the A class.
Example of interface
interface printable { void print(); }
1. class A implements printable {
2. public void print() { System.out.println("Hello"); }
3. public static void main(String args[]) {
4. A obj = new A(); obj.print();
5. }
6. }
Output: Hello
72. Multiple inheritance by interface
A class implements multiple interfaces or an interface extends multiple
interfaces known as multiple inheritance.
73. Multiple inheritance example
1. interface Printable { void print(); }
2.
3. interface Showable { void show(); }
4.
5. class A implements Printable, Showable {
6.
7. public void print() { System.out.println("Hello"); }
8. public void show() { System.out.println("Welcome"); }
9. public static void main(String args[]) {
10. A obj = new A();
11. obj.print();
12. obj.show();
13. }
14. }
Output: Hello
Welcome
74. Interface inheritance
A class implements interface but one interface extends another interface.
1. interface Printable { void print(); }
2. interface Showable extends Printable { void show(); }
3. class Testinterface implements Showable {
4. public void print() {System.out.println("Hello"); }
5. public void show() {System.out.println("Welcome"); }
6. public static void main(String args[]) {
7. Testinterface obj = new Testinterface();
8. obj.print(); obj.show();
9. }
10. }
Output : Hello
Welcome
75. An interface that have no member is known as marker or tagged interface.
Example: Serializable, Cloneable, Remote etc.
They are used to provide essential information to the JVM.
76. Java String
String is an object that represents sequence of characters. Java String is
immutable. An array of characters also works as string.
e.g. char[] ch = {'S', 'i', 'n', 'h', 'g', 'a', 'd' };
String s = new String(ch); is same as:
String s="Sinhgad";
There are two ways to create Strings.
As string literal : String s1="Welcome"; String s2="Welcome";
// s2 will not create new instance
By new keyword : String s = new String("Welcome");
//creates one object and one reference variable
JVM creates a new string object in heap memory and the literal "Welcome"
placed in the string constant pool. The variable 's' refer to the object in heap.
StringBuffer and StringBuilder classes are mutable.
77. Java String Cont …
String Example
1. public class StringExample {
2. public static void main(String args[]) {
3. String s1="java"; //creating string by java string literal
4. char ch[] = {'s','t','r','i','n','g','s'};
5. String s2 = new String(ch); //converting array to string
6. String s3 = new String(“sscs"); //creating by new keyword
7. System.out.println(s1);
8. System.out.println(s2);
9. System.out.println(s3);
10. }
11. }
java
strings
example
78. Java String Cont …
java.lang.String provides methods to perform operations on string values.
Sr. No. Method Description
1 char charAt(int index) returns char value for the index
2 int length() returns string length
3 String substring(int beginIndex) returns substring for given index
4 String substring(int beginIndex,
int endIndex)
returns substring for given begin
index and end index
5 boolean equals(Object another) checks the equality of string with
object
6 boolean isEmpty() checks if string is empty
7 String concat(String str) concatenates specified string
8 String replace(char old, char new) replaces all occurrences of specified
char value
79. Java String Cont …
Sr. No. Method Description
9 int indexOf(int ch) returns specified char value index
10 int indexOf(String substring) returns specified substring index
11 String toLowerCase() returns string in lowercase.
12 String toUpperCase() returns string in uppercase.
13 String split(String regex, int
limit)
returns splitted string matching
regex and limit
14 String trim() returns trimmed string omitting
leading and trailing spaces
80. Java String Cont …
Immutable String
String objects are immutable means unmodifiable or unchangeable.
An example:
1. class Timmutablestring {
2. public static void main(String args[]) {
3. String s="Sinhgad";
4. s.concat("Institute");
//concat() method appends the string at the end
5. System.out.println(s);
6. //will print Sinhgad because strings are immutable objects
7. }
8. }
Output: Sinhgad
81. Java String Cont …
Here two objects are created but 's' reference variable still refers to
"Sinhgad" not to "Sinhgad Institute".
For example:
1. class Testimmutablestring {
2. public static void main(String args[]) {
3. String s = "Sinhgad";
4. s = s.concat(" Institute");
5. System.out.println(s);
6. }
7. }
82. Exception Handling
An Exception is an abnormal condition.
An exception is an event that disrupts the normal flow of the program.
It is an object which is thrown at runtime.
Exception handling is mechanism to handle the runtime errors so that
normal flow of the program execution can be maintained.
Examples;
ClassNotFound, IO, SQL, Remote etc.
An advantage of exception handling is to maintain the normal flow of the
application.
84. Exception Handling Cont …
1. Checked Exception : These extend from Throwable class.
e.g. IOException, SQLException etc.
Checked exceptions are checked at compile-time.
2. Unchecked Exception : These extend from Runtime Exception.
e.g. ArithmeticException, NullPointerException,
ArrayIndexOutOfBoundsException etc.
Unchecked exceptions are checked at runtime.
3. Error : These are irrecoverable
e.g. OutOfMemoryError, VirtualMachineError, AssertionError etc.
Type of exceptions:
85. Exception Handling Cont …
Scenarios where exceptions occur
1) ArithmeticException : If we divide any number by zero.
int a = 50/0; //ArithmeticException
2) NullPointerException : If we have null value in any variable and
performing any operation on it.
String s = null;
System.out.println(s.length()); //NullPointerException
3) NumberFormatException : A string variable that has characters,
converting into digit.
String s="abc";
int i=Integer.parseInt(s);//NumberFormatException
4) ArrayIndexOutOfBoundsException : If we are inserting any value beyond
array capacity.
int a[]=new int[5];
a[10]=50; //ArrayIndexOutOfBoundsException
86. Exception Handling Cont …
• try block enclose the code that might throw an exception.
• Try block must be followed by catch or finally block.
• catch block handle the Exception. It placed after the try block only.
• Finally block can be used to put "cleanup" code such
as closing a file, closing connection etc.
Syntax of try-catch block
1. try {
2. //code that may throw exception
3. } catch(Exception_class_Name ref) { … }
Syntax of try-catch-finally block
1. try {
//code that may throw exception
2. } catch(Exception_class_Name ref) { … }
3. finally{}
try-catch-finally block
88. Exception Handling Cont …
1.public class Testtrycatch {
2. public static void main(String args[]) {
3. try {
4. int data=50/0;
5. } catch(ArithmeticException e) { System.out.println(e); }
6. System.out.println(“Rest of the code...");
7. }
8.}
Output:
Exception in thread main java.lang.ArithmeticException: divide by zero
Rest of the code...
Exception handling example
89. Exception Handling Cont …
Use of finally block
1. public class TestFinallyBlock {
2. public static void main(String args[]){
3. try{
4. int data=25/0;
5. System.out.println(data);
6. }
7. catch(ArithmeticException e){System.out.println(e);}
8. finally{System.out.println("finally block always executed");}
9. System.out.println("rest of the code...");
10. }
11. }
Output:
Exception in thread main java.lang.ArithmeticException: Divide by zero
finally block always executed
rest of the code...
90. Exception Handling Cont …
Nested try block : The try block within a try block is known as nested
try block in java.
Nested try example
Simple example of java nested try block.
1. class NestedExcep{
2. public static void main(String args[]){
3. try { try { System.out.println(“to do divide");
4. int b =39/0;
5. } catch(ArithmeticException e) { S.O.P(e); }
6. try { int a[]=new int[5];
7. a[5]=4;
8. } catch (ArrayIndexOutOfBoundsException e) { S.O.P(e);}
9. System.out.println("other statement);
10. } catch(Exception e){System.out.println("handeled");}
11. System.out.println("normal flow..");
12. }
13. }
91. Throw keyword explicitly throws an exception.
Throw keyword throws checked or unchecked exception.
Throw keyword is used to throw custom exception.
syntax : throw ExceptionObject;
Program example
1. public class TestThrow{
2. static void validate(int age) {
3. if (age<18)
4. throw new ArithmeticException("not valid");
5. else System.out.println("welcome to vote");
6. }
7. public static void main(String args[]) {
8. validate(13);
9. System.out.println("rest of the code...");
10. }
11. }
Output: Exception in thread main java.lang.ArithmeticException: not valid
Exception Handling Cont …
throw keyword
92. Exception Handling Cont …
Used to declare an exception.
Gives an information to the programmer that there may occur an exception.
Exception Handling is used to handle the checked exceptions.
If occurs unchecked exception it is programmers fault.
throws example
1. import java.io.IOException;
2. class Testthrows{
3. void m() throws IOException
4. { throw new IOException("device error"); //checked exception }
5. void n()
{ try { m(); }
catch(Exception e) { System.out.println("exception handled"); }
1. public static void main(String args[]){
2. Testthrows obj = new Testthrows();
3. obj.n(); System.out.println("normal flow...");
4. }
5. }
Output: exception handled
normal flow
throws keyword
93. Exception Handling Cont …
throw throws
1) Used to throw an exception. Used to declare an exception.
2) checked exception can not be
propagated with throw.
checked exception can be
propagated with throws.
3) throw is followed by an instance. throws is followed by class.
4) throw is used within the
method.
throws is used with the method
signature.
5) We cannot throw multiple
exceptions
We can declare multiple exception
e.g. public void method() throws
IOException, SQLException.
Difference between throw and throws keywords:
94. User created exception is known as custom exception or user-defined
exception.
Custom exceptions customize the exception according to user need .
Java Custom Exception
Example
1. class InvalidAgeException extends Exception
2. { InvalidAgeException(String s) { super(s); } }
3. class TestCustomException {
4. static void validate(int age) throws InvalidAgeException
5. { if (age<18) throw new InvalidAgeException("not valid");
6. else System.out.println("welcome");
7. }
8. public static void main(String args[]) {
9. try { validate(13);
10. } catch(Exception m) {S.O.P("Exception occurred: "+m;}
11. System.out.println("rest of the code...");
12. } }
Output: Exception occured: InvalidAgeException: not valid rest of the code...
95. Packages
A package is a group of classes, interfaces and sub-packages.
Package is a built-in or user-defined.
Built-in packages e.g. java, lang, awt, javax, swing, net, io, util, sql etc.
Advantages of Java
Package
1. Categorize the
classes, interfaces to
easily maintain.
2. Provides access
protection.
3. Removes naming
collision.
Packages cont …
96. Packages cont …
The package keyword is used to create a package.
1. // save as Simple.java
2. package mypack;
3. public class Simple {
4. public static void main(String args[]) {
5. System.out.println("Welcome to package"); }
6. }
Compile package as
javac -d directory javafilename
e.g. javac -d . Simple.java
-d switch specifies the destination to put the generated class file.
e.g. 'd:/abc' or for same directory use . (dot).
Example of package
97. Packages cont …
Example of package
Three ways to access the class from outside the package.
1. import package.*;
2. import package.classname; or
3. fully qualified name;
Run java package program by command
java mypack.Simple
Use fully qualified name e.g. mypack.Simple to run the class.
Example of package
1. // save by A.java
2. package pack;
3. public class A {
4. public void msg() { System.out.println("Hello"); }
5. }
98. Packages cont …
1. // save by B.java
2. import pack.*;
3. class B {
4. public static void main(Strincontg args[]) {
5. A obj = new A(); obj.msg();
6. } }
7. Output:Hello
Example of package cont …
1. import pack.A;
2. class B {
3. public static void main(String args[]) {
4. A obj = new A(); obj.msg();
5. } }
6. Output: Hello
pack.A obj = new pack.A(); //using fully qualified name
99. Packages cont …
Sequence of the program code
Subpackage
Package inside the package is called
the subpackage.
subpackage should be created to
categorize the package further.
1. Example of Subpackage
2. package com.myjava.core;
3. class Simple {
4. public static void main(String args[]){
5. System.out.println("Hello subpackage");
6. } }
100. Packages cont …
The access modifiers specify accessibility (scope) of a data member,
method or class.
There are 4 types of access modifiers:
1. private
2. default
3. protected
4. Public
Access Modifiers in java
• The private access modifier is accessible only within class.
• If you don't use any modifier, it is treated as default. The default
modifier is accessible only within package.
• The protected access modifier is accessible within package and
outside the package but through inheritance only.
• The public access modifier is accessible everywhere.
Editor's Notes
Object e.g. chair, bike, marker, pen, table, car etc. , tangible and intangible.