This document provides class declarations for various classes in the java.lang package. It summarizes each class including its purpose and fields. Some key classes described are Boolean, Byte, Character, Class, Double, Float, Integer, Long, Number, Object, String, StringBuffer. The document also provides the class declaration for each class listed.
The document discusses object-oriented programming concepts like inheritance, subclasses, and polymorphism. It provides examples of different forms of inheritance including:
1. Inheritance for specialization where a child class is a specialized form of the parent class and the principle of substitutability holds.
2. Inheritance for specification where a parent class specifies behavior but doesn't implement it, and child classes implement the behavior, like with interfaces and abstract classes.
3. Inheritance for construction where a child class inherits functionality from a parent but may change method names/parameters, primarily for code reuse rather than creating a subtype relationship.
The document discusses object oriented programming concepts related to packages, interfaces, and their implementation in Java. It defines what packages and interfaces are, how to create and access packages, differences between classes and interfaces, how to define and implement interfaces, and examples of applying packages and interfaces in Java code.
The document provides definitions and explanations of various object-oriented programming concepts in Delphi such as classes, objects, visibility of class members, inheritance, abstract classes, interfaces, constructors, virtual functions, polymorphism, late binding, encapsulation, properties, exceptions handling, and runtime type information (RTTI). It discusses these concepts through questions and answers. Key points covered include the relationship between classes and objects, differences between visibility levels of class members, how inheritance allows the creation of subclasses, rules around abstract classes and methods, limitations of interfaces, how to define and overload constructors and functions, use of virtual functions and polymorphism, and how RTTI is used.
Java is an object-oriented programming language that is architecture-neutral, portable, distributed, high-performance, interpreted, multithreaded, robust, dynamic, and secure. It uses bytecode that is translated from Java code and interpreted by the Java Virtual Machine. Java can be used for applets, networking, internationalization, security, object serialization, and database connectivity. It is platform independent because Java code is compiled into bytecode that runs consistently on any Java platform. The document then discusses control flow statements, decision-making statements, operators, object-oriented principles of encapsulation, inheritance, and polymorphism, classes and objects, methods, access specifiers, and inheritance types in Java.
This document provides an introduction to Java and object-oriented programming concepts. It discusses how Java was designed to develop advanced software for network devices and systems. It then defines Java as an object-oriented programming language where code written to model real-world objects is called a class. The document also explains key object-oriented programming concepts like classes, objects, encapsulation, inheritance and polymorphism. It provides details on the object lifecycle of creation, usage and disposal in Java.
The document discusses key concepts of object-oriented programming including objects, classes, inheritance, polymorphism, encapsulation, and abstraction. It provides examples of constructors, method overloading and overriding, interfaces, and packages in Java.
The document discusses basic Java concepts including identifiers, keywords, literals, primitive data types, variables, operators, control flow statements, classes, methods, inheritance, polymorphism, packages and modifiers. It provides definitions and examples of key concepts like classes, objects, methods, inheritance, polymorphism, packages, modifiers, variables and data types. It also lists Java keywords, reserved words and literals.
Inheritance and polymorphism are key concepts in object-oriented programming that allow for code reuse. Inheritance allows a subclass to inherit attributes and behaviors from a superclass, while also adding its own attributes and behaviors. Polymorphism allows subclasses to override or modify inherited behaviors from the superclass. This allows subclasses to be treated as their superclass type while still maintaining their specific behaviors. The document discusses inheritance in Java including inheriting classes, the super reference, overriding and final methods/classes, abstract classes, and interfaces. It also covers polymorphism, access modifiers, and packages in Java.
The document discusses object-oriented programming concepts like inheritance, subclasses, and polymorphism. It provides examples of different forms of inheritance including:
1. Inheritance for specialization where a child class is a specialized form of the parent class and the principle of substitutability holds.
2. Inheritance for specification where a parent class specifies behavior but doesn't implement it, and child classes implement the behavior, like with interfaces and abstract classes.
3. Inheritance for construction where a child class inherits functionality from a parent but may change method names/parameters, primarily for code reuse rather than creating a subtype relationship.
The document discusses object oriented programming concepts related to packages, interfaces, and their implementation in Java. It defines what packages and interfaces are, how to create and access packages, differences between classes and interfaces, how to define and implement interfaces, and examples of applying packages and interfaces in Java code.
The document provides definitions and explanations of various object-oriented programming concepts in Delphi such as classes, objects, visibility of class members, inheritance, abstract classes, interfaces, constructors, virtual functions, polymorphism, late binding, encapsulation, properties, exceptions handling, and runtime type information (RTTI). It discusses these concepts through questions and answers. Key points covered include the relationship between classes and objects, differences between visibility levels of class members, how inheritance allows the creation of subclasses, rules around abstract classes and methods, limitations of interfaces, how to define and overload constructors and functions, use of virtual functions and polymorphism, and how RTTI is used.
Java is an object-oriented programming language that is architecture-neutral, portable, distributed, high-performance, interpreted, multithreaded, robust, dynamic, and secure. It uses bytecode that is translated from Java code and interpreted by the Java Virtual Machine. Java can be used for applets, networking, internationalization, security, object serialization, and database connectivity. It is platform independent because Java code is compiled into bytecode that runs consistently on any Java platform. The document then discusses control flow statements, decision-making statements, operators, object-oriented principles of encapsulation, inheritance, and polymorphism, classes and objects, methods, access specifiers, and inheritance types in Java.
This document provides an introduction to Java and object-oriented programming concepts. It discusses how Java was designed to develop advanced software for network devices and systems. It then defines Java as an object-oriented programming language where code written to model real-world objects is called a class. The document also explains key object-oriented programming concepts like classes, objects, encapsulation, inheritance and polymorphism. It provides details on the object lifecycle of creation, usage and disposal in Java.
The document discusses key concepts of object-oriented programming including objects, classes, inheritance, polymorphism, encapsulation, and abstraction. It provides examples of constructors, method overloading and overriding, interfaces, and packages in Java.
The document discusses basic Java concepts including identifiers, keywords, literals, primitive data types, variables, operators, control flow statements, classes, methods, inheritance, polymorphism, packages and modifiers. It provides definitions and examples of key concepts like classes, objects, methods, inheritance, polymorphism, packages, modifiers, variables and data types. It also lists Java keywords, reserved words and literals.
Inheritance and polymorphism are key concepts in object-oriented programming that allow for code reuse. Inheritance allows a subclass to inherit attributes and behaviors from a superclass, while also adding its own attributes and behaviors. Polymorphism allows subclasses to override or modify inherited behaviors from the superclass. This allows subclasses to be treated as their superclass type while still maintaining their specific behaviors. The document discusses inheritance in Java including inheriting classes, the super reference, overriding and final methods/classes, abstract classes, and interfaces. It also covers polymorphism, access modifiers, and packages in Java.
This document provides an overview of Java basics, including:
- Java is an object-oriented programming language and platform that allows code to run on many systems.
- Java code is compiled to bytecode that runs on a Java Virtual Machine (JVM).
- Key Java technologies include the JVM, Java Runtime Environment (JRE), and Java Software Development Kit (SDK).
- Java supports object-oriented programming concepts like classes, objects, inheritance, interfaces, and polymorphism.
- The document outlines language syntax rules and concepts like variables, methods, and access modifiers.
Java is an object-oriented programming language. Key aspects of Java include:
- It is platform independent and runs on a virtual machine.
- Programs are written in classes with methods. The main method is where execution begins.
- Common operations include accepting user input, printing output, and performing math functions.
- Java supports concepts like inheritance, polymorphism, abstraction and encapsulation.
- The language does not support pointers, structures or multiple inheritance.
The document discusses access modifiers in Java and their usage with variables, functions, and classes at different levels. It explains that access modifiers like private, protected, default, and public determine whether elements are visible from within the same class, package, subclass, or any class. Private is most restrictive while public is most accessible. It also covers other concepts like static methods, inheritance, polymorphism, abstract classes, interfaces and exception handling in Java.
In this you learn about
Access Modifiers in Java / Visibility Modifiers in Java
1. Default access modifier
2. private access modifier
3. protected access modifier
4. public access modifier
Ideal for learning the basics of java, and can also be used as a school project for class 10 and 12. The document contains illustrative pictures, and carefully selected information to make the basics of java strong. Pls ignore small spelling mistakes made.
The document discusses advanced object-oriented programming concepts in Java, including abstract classes, interfaces, packages, and inheritance. It explains how to create and extend abstract classes, use interfaces to allow multiple inheritance, store related constants in interfaces, and organize classes into packages. Dynamic method binding and creating arrays of superclass references that hold subclass objects are also covered. The key benefits of interfaces, abstract classes, inheritance and packages for software reuse and flexibility are highlighted.
20 most important java programming interview questionsGradeup
The document discusses 20 important Java programming interview questions. It covers topics such as the differences between interfaces and abstract classes, when to use abstract classes versus interfaces, what the Serializable interface does, how to force garbage collection, the differences between StringBuffer and StringBuilder, checked and unchecked exceptions, how Java allocates stack and heap memory, Java reflection, the Java Virtual Machine, the differences between JDK and JRE, and more.
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 a summary of questions for a C# interview. It includes general C# questions, class questions, method and property questions, events and delegates questions, XML documentation questions, debugging and testing questions, ADO.NET and database questions, and assembly questions. The author gathered these questions from various sources and their own experience, and is seeking feedback to improve or suggest new questions.
This document provides a summary of key Java concepts and answers to common Java interview questions. It begins with an introduction explaining what the presentation covers. The bulk of the document consists of questions and detailed answers on topics like exceptions, abstract classes, strings, arrays, collections, inheritance and polymorphism.
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.
Inheritance is a mechanism in Java that allows one class to acquire the properties (fields and methods) of another class. The class that inherits is called the subclass, and the class being inherited from is called the superclass. This allows code reuse and establishes an is-a relationship between classes. There are three main types of inheritance in Java: single, multilevel, and hierarchical. Method overriding and dynamic method dispatch allow subclasses to provide their own implementation of methods defined in the superclass.
Java supports key object-oriented programming concepts like abstraction, encapsulation, inheritance and polymorphism. Abstraction hides unnecessary details, encapsulation wraps data and functions into a class, inheritance allows classes to inherit attributes and behaviors from parent classes, and polymorphism allows one interface to multiple forms. Java also uses bytecode, JIT compilation, and dynamic binding. Interfaces allow classes to implement common behaviors without sharing an inheritance relationship. Abstract classes support inheritance and require subclasses to implement abstract methods.
1. Inheritance in Java allows classes to extend other classes and interfaces to implement other interfaces. This allows code reuse and establishes type constraints.
2. Abstract classes can contain both abstract and non-abstract methods while interfaces contain only abstract methods. Interfaces establish contracts that implementing classes must follow.
3. When constructing objects with inheritance, superclass constructors are called before subclass constructors. Abstract classes and interfaces allow incomplete implementations to be extended.
This document provides an overview of programming in Java. It outlines the course objectives which are to teach object-oriented programming fundamentals in Java, how to develop Java applications and applets, and create GUI-based apps that run across platforms. It then lists some reference books and introduces basic concepts like Java's history, data types, variables, and control structures. The document also compares Java to C/C++ and outlines the Java compilation and interpretation process.
This document contains 20 interview questions related to Java. It covers topics such as:
- The differences between constructors and methods, final and static keywords, and the purpose of the Void class.
- Details about finalize methods, just-in-time compilation, abstraction, encapsulation, inheritance, polymorphism, and method overloading and overriding.
- Questions about byte code, class vs instance variables, local variables, and class vs instance methods.
- Definitions of interfaces, abstract classes, access specifiers, identifiers, and literals.
- Questions about the name Java, calling 'sun' packages, Java releases, constructors vs methods, static vs non-static variables, while
Superclasses, and Subclasses, Overriding and Hiding Methods, Polymorphism, Inheritance Hierarchies, Super keyword, Final Classes and Methods, Abstract,
Classes and Methods, Nested classes & Inner Classes,
finalization and garbage collection.
VSM is a sourcing agency in India with over 30 years of experience in textiles, apparel, and accessories. They ensure reliable and timely delivery of high quality products from India. VSM works with a network of vendors and manufacturers to source a wide variety of latest fashion products at competitive prices. Their experienced staff organize prompt deliveries while maintaining strict quality control.
1) The Park Plaza Sweet Shoppe in the Bronx was an important gathering place for teenagers in the 1950s. They would meet there before and after dances, movies, and other activities.
2) The owners knew all the teenagers by name and allowed them to spend hours talking and hanging out without disturbing other customers. It felt like a home away from home.
3) In the summer, the teenagers engaged in mischievous activities like sneaking into movies and having shaving cream fights. These antics built strong bonds of friendship and memories that lasted lifetimes.
This document provides an overview of Java basics, including:
- Java is an object-oriented programming language and platform that allows code to run on many systems.
- Java code is compiled to bytecode that runs on a Java Virtual Machine (JVM).
- Key Java technologies include the JVM, Java Runtime Environment (JRE), and Java Software Development Kit (SDK).
- Java supports object-oriented programming concepts like classes, objects, inheritance, interfaces, and polymorphism.
- The document outlines language syntax rules and concepts like variables, methods, and access modifiers.
Java is an object-oriented programming language. Key aspects of Java include:
- It is platform independent and runs on a virtual machine.
- Programs are written in classes with methods. The main method is where execution begins.
- Common operations include accepting user input, printing output, and performing math functions.
- Java supports concepts like inheritance, polymorphism, abstraction and encapsulation.
- The language does not support pointers, structures or multiple inheritance.
The document discusses access modifiers in Java and their usage with variables, functions, and classes at different levels. It explains that access modifiers like private, protected, default, and public determine whether elements are visible from within the same class, package, subclass, or any class. Private is most restrictive while public is most accessible. It also covers other concepts like static methods, inheritance, polymorphism, abstract classes, interfaces and exception handling in Java.
In this you learn about
Access Modifiers in Java / Visibility Modifiers in Java
1. Default access modifier
2. private access modifier
3. protected access modifier
4. public access modifier
Ideal for learning the basics of java, and can also be used as a school project for class 10 and 12. The document contains illustrative pictures, and carefully selected information to make the basics of java strong. Pls ignore small spelling mistakes made.
The document discusses advanced object-oriented programming concepts in Java, including abstract classes, interfaces, packages, and inheritance. It explains how to create and extend abstract classes, use interfaces to allow multiple inheritance, store related constants in interfaces, and organize classes into packages. Dynamic method binding and creating arrays of superclass references that hold subclass objects are also covered. The key benefits of interfaces, abstract classes, inheritance and packages for software reuse and flexibility are highlighted.
20 most important java programming interview questionsGradeup
The document discusses 20 important Java programming interview questions. It covers topics such as the differences between interfaces and abstract classes, when to use abstract classes versus interfaces, what the Serializable interface does, how to force garbage collection, the differences between StringBuffer and StringBuilder, checked and unchecked exceptions, how Java allocates stack and heap memory, Java reflection, the Java Virtual Machine, the differences between JDK and JRE, and more.
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 a summary of questions for a C# interview. It includes general C# questions, class questions, method and property questions, events and delegates questions, XML documentation questions, debugging and testing questions, ADO.NET and database questions, and assembly questions. The author gathered these questions from various sources and their own experience, and is seeking feedback to improve or suggest new questions.
This document provides a summary of key Java concepts and answers to common Java interview questions. It begins with an introduction explaining what the presentation covers. The bulk of the document consists of questions and detailed answers on topics like exceptions, abstract classes, strings, arrays, collections, inheritance and polymorphism.
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.
Inheritance is a mechanism in Java that allows one class to acquire the properties (fields and methods) of another class. The class that inherits is called the subclass, and the class being inherited from is called the superclass. This allows code reuse and establishes an is-a relationship between classes. There are three main types of inheritance in Java: single, multilevel, and hierarchical. Method overriding and dynamic method dispatch allow subclasses to provide their own implementation of methods defined in the superclass.
Java supports key object-oriented programming concepts like abstraction, encapsulation, inheritance and polymorphism. Abstraction hides unnecessary details, encapsulation wraps data and functions into a class, inheritance allows classes to inherit attributes and behaviors from parent classes, and polymorphism allows one interface to multiple forms. Java also uses bytecode, JIT compilation, and dynamic binding. Interfaces allow classes to implement common behaviors without sharing an inheritance relationship. Abstract classes support inheritance and require subclasses to implement abstract methods.
1. Inheritance in Java allows classes to extend other classes and interfaces to implement other interfaces. This allows code reuse and establishes type constraints.
2. Abstract classes can contain both abstract and non-abstract methods while interfaces contain only abstract methods. Interfaces establish contracts that implementing classes must follow.
3. When constructing objects with inheritance, superclass constructors are called before subclass constructors. Abstract classes and interfaces allow incomplete implementations to be extended.
This document provides an overview of programming in Java. It outlines the course objectives which are to teach object-oriented programming fundamentals in Java, how to develop Java applications and applets, and create GUI-based apps that run across platforms. It then lists some reference books and introduces basic concepts like Java's history, data types, variables, and control structures. The document also compares Java to C/C++ and outlines the Java compilation and interpretation process.
This document contains 20 interview questions related to Java. It covers topics such as:
- The differences between constructors and methods, final and static keywords, and the purpose of the Void class.
- Details about finalize methods, just-in-time compilation, abstraction, encapsulation, inheritance, polymorphism, and method overloading and overriding.
- Questions about byte code, class vs instance variables, local variables, and class vs instance methods.
- Definitions of interfaces, abstract classes, access specifiers, identifiers, and literals.
- Questions about the name Java, calling 'sun' packages, Java releases, constructors vs methods, static vs non-static variables, while
Superclasses, and Subclasses, Overriding and Hiding Methods, Polymorphism, Inheritance Hierarchies, Super keyword, Final Classes and Methods, Abstract,
Classes and Methods, Nested classes & Inner Classes,
finalization and garbage collection.
VSM is a sourcing agency in India with over 30 years of experience in textiles, apparel, and accessories. They ensure reliable and timely delivery of high quality products from India. VSM works with a network of vendors and manufacturers to source a wide variety of latest fashion products at competitive prices. Their experienced staff organize prompt deliveries while maintaining strict quality control.
1) The Park Plaza Sweet Shoppe in the Bronx was an important gathering place for teenagers in the 1950s. They would meet there before and after dances, movies, and other activities.
2) The owners knew all the teenagers by name and allowed them to spend hours talking and hanging out without disturbing other customers. It felt like a home away from home.
3) In the summer, the teenagers engaged in mischievous activities like sneaking into movies and having shaving cream fights. These antics built strong bonds of friendship and memories that lasted lifetimes.
A Movement for Improvement; Part 2 - Case Study 3, Part 2----Alexandra E. P. Dahl
The document summarizes a group project for a communications class where the group worked with the non-profit organization Room for Grace. It discusses how the group applied concepts around group relationships and roles from their textbook. Each member served different roles, such as the orienter, initiator, information seeker, and encourager. They worked well together as a team to research the organization and accomplish tasks, though one member was more quiet and difficult to communicate with. In the end, the group was able to help improve the mission of Room for Grace in the community.
David Peak is seeking a contracting Business Analyst role based in Sydney, Australia starting in January 2017. He has over 10 years of experience in various Business Analyst and IT roles, including at Lloyds Banking Group, ACE Insurance, and Colt Telecom. His experience includes requirements gathering, system testing, and delivery of projects in industries like banking, insurance, and telecommunications.
Amplify & MaRS DD - Financial FundementalsKyle Turriff
This document provides an overview of key financial concepts and metrics for entrepreneurs. It discusses common mistakes entrepreneurs make related to finances, including a lack of proper documentation and inappropriate draws. The agenda includes reviewing financial terms, metrics like income statements and balance sheets, and accessing financing. Key financial metrics covered are income statements, gross margin, contribution margin, net income, breakeven analysis, and balance sheet basics. Accessing financing through traditional debt is discussed alongside factors like debt ratios, while venture capital is presented as trading equity for funding to meet milestones.
This short document promotes creating presentations using Haiku Deck on SlideShare. It encourages the reader to get started making their own Haiku Deck presentation by providing a button to click to begin the process. In a single sentence, it pitches presentation creation software.
ExpLOD: a framework for explaining recommendations based on the Linked Open D...Fedelucio Narducci
The document presents ExpLOD, a framework for explaining recommendations based on the Linked Open Data cloud. ExpLOD addresses the problem that recommendation processes can be viewed as "black boxes" by connecting user preferences to recommendations through Linked Open Data properties. The framework represents user profiles and recommendations as DBpedia nodes and builds a graph model linking them. It selects explanatory properties based on their connections to the user profile and recommendation. ExpLOD then generates natural language explanations and was found to increase the transparency, persuasiveness, engagement and trust of recommendations compared to baselines in an experimental user study.
Este documento describe los diferentes tipos de conflictos que pueden surgir en las organizaciones, como los conflictos de roles, objetivos, entre departamentos e interpersonales. También explica que el conflicto no necesariamente es negativo y puede conducir a beneficios como mejorar la comunicación, definir problemas y estimular la creatividad. La mejor forma de manejar los conflictos es reconocerlos, definir el problema, considerar diferentes perspectivas, diseñar soluciones mutuamente beneficiosas y comprometerse con la solución elegida.
The document discusses key concepts in Java including classes, objects, methods, and command line arguments. A class defines common properties and behaviors for objects through fields and methods. Objects are instantiated from classes and can access fields and methods using dot notation. Command line arguments allow passing data into a Java application and are accessed through the args parameter in the main method.
This document provides an overview of Java utilities and collection classes. It discusses the Java Math class and methods for numeric operations. It also describes wrapper classes for primitive data types and lists the eight primitive types in Java. Finally, it provides an example of using the Collections class to sort, reverse, shuffle a list and check element frequencies.
This document provides an introduction to the Java programming language. It discusses the history and components of Java, including the Java language, platform, and tools. It then explains some key Java concepts like object-oriented programming, classes, objects, inheritance, and interfaces. It provides examples of how to write a simple Java program and declare methods. It also compares static and instance members and discusses abstract classes and when to use interfaces versus abstract classes.
The document provides summaries of key Java concepts like static blocks, constructors, method overriding, the super keyword, method overloading vs overriding, abstract classes vs interfaces, why Java is platform independent, JIT compilers, bytecode, encapsulation, the differences between this() and super(), classes, objects, methods, and constructors in Java. It also answers common interview questions about the main() method, access modifiers, and the differences between C++ and Java.
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.
Generics and Collections
The document discusses generics and collections in Java. It defines generics as a style of programming that allows algorithms to operate on objects of different types while providing compile-time type safety. The Java collections framework supports generics to specify the type of objects stored in a collection. Common collection classes like ArrayList, LinkedList, and HashMap are discussed along with their key characteristics.
This document discusses objects and classes in Java. It begins by defining what a class is - a template that defines common properties of objects. Everything in a Java program must be encapsulated within a class. A class defines an object's state via fields and behavior via methods. The document then discusses how to define classes by specifying fields, methods, and constructors. It provides examples of creating objects from classes and accessing object members. The document also covers key object-oriented programming concepts like encapsulation and inheritance.
The document discusses key concepts related to classes and objects in object-oriented programming. It defines class, object, class variables, object variables, class methods, and object methods. It explains that a class is a blueprint or template for creating objects, and that every object is built from a class. It also provides examples of how to write a class in different programming languages like ActionScript 3 and Visual Basic. The document then discusses other important OOP concepts like inheritance, polymorphism, exception handling, and common programming structures like arrays, foreach loops, and GUI components.
This document provides an overview of object-oriented programming concepts including abstraction, encapsulation, classes, objects, methods, constructors, inheritance, polymorphism, and interfaces. It explains that classes act as blueprints for objects, describing their data and behaviors. Objects are instances of classes that have state stored in attributes and behaviors defined by methods. Key features of OOP like inheritance, encapsulation, and polymorphism are discussed at a high level.
Java was created in 1991 by James Gosling, Mike Sheridan, and Patrick Naughton at Sun Microsystems. It has three editions: Java ME for limited devices, Java SE as the core platform for desktops and servers, and Java EE for large enterprise applications. Java code is compiled into bytecode that runs on a Java Virtual Machine (JVM) making Java portable across platforms. Key principles of Java include being object-oriented, secure, and platform independent.
ITT 202 PRINCIPLES OF OBJECT ORIENTED TECHNIQUEVinishA23
The document discusses various object-oriented programming concepts in Java:
1. Objects are instances of classes that contain both data and functions. Classes act as blueprints for creating objects.
2. Inheritance allows subclasses to inherit attributes and behaviors from parent classes. Subclasses can override methods from parent classes.
3. Polymorphism allows functions to take different forms - either by function overloading or overriding. Overloading relies on static binding at compile time, while overriding uses dynamic binding at runtime.
The document discusses the history and development of the Java programming language. It describes how James Gosling initiated the Java project in 1991. Sun Microsystems later released Java 1.0 in 1995 with the promise of "Write Once, Run Anywhere". Sun later released much of Java as open-source software in 2006 and 2007. The document also provides overviews of Java concepts like object-oriented programming, the Java Virtual Machine, and classloaders.
Full CSE 310 Unit 1 PPT.pptx for java languagessuser2963071
This document discusses Java programming fundamentals including naming conventions, data types, literals, and writing a basic Java program. It covers lowercase and uppercase naming rules for variables, methods, and classes. It also describes numeric, boolean, character, and string literals. Key data types like int, float, char, and their ranges are explained. The document provides examples of type conversion, casting, and type promotion in expressions. It concludes with steps for compiling and running a Java program.
Inheritance allows classes to inherit properties and behaviors from parent classes in Java and C#. Both languages support simple, multilevel, and hierarchical inheritance through the use of extends and implements keywords. Java does not support multiple inheritance directly but allows classes to inherit from one parent class and implement multiple interfaces. Constructors and methods can be called or overridden in subclasses using the super and this keywords respectively.
Internet and Web Technology (CLASS-15) [JAVA Basics] | NIC/NIELIT Web Technol...Ayes Chinmay
The document discusses Java programming and object-oriented programming concepts. It includes:
- An overview of Java including its history, platforms, and creator James Gosling.
- Explanations of object-oriented programming concepts in Java including classes, objects, encapsulation, inheritance, polymorphism, and abstraction with examples.
- Code samples demonstrating Java syntax and basic programming.
- Questions about HTML tags, Apache Tomcat, JavaScript functions, and alternative scripting languages.
OCA Java SE 8 Exam Chapter 1 Java Building Blocksİbrahim Kürce
The document discusses key concepts in Java including classes, objects, fields, methods, variables, primitive types, reference types, and memory management. It explains that classes are the basic building blocks in Java programs and contain fields and methods. Objects are instances of classes that exist in memory. The document also covers variable scope, default initialization, and garbage collection in Java.
Java interview questions and answers for cognizant By Data Council PunePankaj kshirsagar
Java is an object-oriented programming language used widely for both desktop and mobile applications. It is portable, platform-independent, robust, and interpreted. The document lists 10 common Java interview questions and provides detailed answers on topics like Java features, objects, classes, JDK vs JRE vs JVM, StringBuffer vs StringBuilder, loops, and the final keyword. Key Java concepts covered include object-oriented programming, memory management, garbage collection, and polymorphism.
This document provides an overview of object oriented programming concepts in Java including classes, objects, encapsulation, inheritance, polymorphism and more. It also outlines the syllabus for a course on OOP with Java, covering topics like arrays, strings, vectors, exception handling, GUI programming and more. Finally, it provides some examples of basic Java code.
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.
An interface in Java is a blueprint of a class that defines a standard for what methods a class must include. Interfaces provide full abstraction since none of its methods have a body, while abstract classes provide partial abstraction since they can contain both abstract and concrete methods. Interfaces are used to achieve abstraction and multiple inheritance in Java. Common functionalities can be defined in an interface and implemented differently in classes.
1. Java.lang package tutorial
Java.util package contains the classes that are fundamental to
the design of the Java programming language.
Java.langBooleanClass
The java.lang.Boolean class wraps a value of the primitive
type boolean in an object. An object of type Boolean contains
a single field whose type is boolean.
Class declaration
Following is the declaration for java.lang.Boolean class:
public final class Boolean
extends Object
implements Serializable, Comparable<Boolean>
Java.lang.Byte Class
The java.lang.Byte class wraps a value of primitive type byte
in an object. An object of type Byte contains a single field
whose type is byte.
Class declaration
Following is the declaration for java.lang.Byte class:
public final class Byte
2. extends Number
implements Comparable<Byte>
Java.lang.Character Class
The java.lang.Character class wraps a value of the primitive
type char in an object. An object of type Character contains a
single field whose type is char.
Class declaration
Following is the declaration for java.lang.Character class:
public final class Character
extends Object
implements Serializable, Comparable<Character>
Java.lang.Character.Subset Class
The java.lang.Character.Subset class instances represent
particular subsets of the Unicode character set. The only family
of subsets defined in the Character class is UnicodeBlock.
Class declaration
Following is the declaration
for java.lang.Character.Subset class:
public static class Character.Subset
3. extends Object
Java.lang.Character.UnicodeBlock Class
The java.lang.Character.UnicodeBlock class is a family of
character subsets representing the character blocks in the
Unicode specification. Character blocks generally define
characters used for a specific script or purpose.
Class declaration
Following is the declaration
for java.lang.Character.UnicodeBlock class:
public static final class Character.UnicodeBlock
extends Character.Subset
Java.lang.Class Class
The java.lang.Class class instance represent classes and
interfaces in a running Java application.It has no public
constructor.
Class declaration
Following is the declaration for java.lang.Class class:
4. public final class Class<T>
extends Object
implements Serializable, GenericDeclaration, Type,
AnnotatedElement
Java.lang.ClassLoader Class
The java.lang.ClassLoader class is an object that is
responsible for loading classes. This class is an abstract class.
It may be used by security managers to indicate security
domains.
Class declaration
Following is the declaration for java.lang.ClassLoader class:
public abstract class ClassLoader
extends Object
Java.lang.Compiler Class
The java.lang.Compiler class is provided to support Java-to-
native-code compilers and related services. By design, it
serves as a placeholder for a JIT compiler implementation.
Class declaration
Following is the declaration for java.lang.Compiler class:
public final class Compiler
5. extends Object
Java.lang.Double Class
The java.lang.Double class wraps a value of the primitive type
double in an object. An object of type Double contains a single
field whose type is double.
Class declaration
Following is the declaration for java.lang.Double class:
public final class Double
extends Number
implements Comparable<Double>
Java.lang.Enum Class
The java.lang.Enum class is the common base class of all
Java language enumeration types.
Class declaration
Following is the declaration for java.lang.Enum class:
public abstract class Enum<E extends Enum<E>>
extends Object
implements Comparable<E>, Serializable
6. Java.lang.Float Class
The java.lang.Float class wraps a value of primitive type float
in an object. An object of type Float contains a single field
whose type is float.
Class declaration
Following is the declaration for java.lang.Float class:
public final class Float
extends Number
implements Comparable<Float>
Java.lang.InheritableThreadLocal Class
The java.lang.InheritableThreadLocal class extends
ThreadLocal to provide inheritance of values from parent
thread to child thread: when a child thread is created, the child
receives initial values for all inheritable thread-local variables
for which the parent has values.
Class declaration
Following is the declaration
for java.lang.InheritableThreadLocal class:
public class InheritableThreadLocal<T>
extends ThreadLocal<T>
7. Java.lang.Integer Class
The java.lang.Integer class wraps a value of the primitive type
int in an object. An object of type Integer contains a single field
whose type is int.
Class declaration
Following is the declaration for java.lang.Integer class:
public final class Integer
extends Number
implements Comparable<Integer>
Java.lang.Long Class
The java.lang.Long class wraps a value of the primitive type
long in an object. An object of type Long contains a single field
whose type is long.
Class declaration
Following is the declaration for java.lang.Long class:
public final class Long
extends Number
implements Comparable<Long>
8. Java.lang.Number Class
The java.lang.Number class is the superclass of classes
BigDecimal, BigInteger, Byte, Double, Float, Integer, Long, and
Short.The Subclasses of Number must provide methods to
convert the represented numeric value to byte, double, float,
int, long, and short.
Class declaration
Following is the declaration for java.lang.Number class:
public abstract class Number
extends Object
implements Serializable
Java.lang.Object Class
The java.lang.Object class is the root of the class hierarchy.
Every class has Object as a superclass. All objects, including
arrays, implement the methods of this class.
Class declaration
Following is the declaration for java.lang.Object class:
public class Object
9. Java.lang.Package Class
The java.lang.Package class contain version information
about the implementation and specification of a Java package
Class declaration
Following is the declaration for java.lang.Package class:
public class Package
extends Object
implements AnnotatedElement
Java.lang.Process Class
The java.lang.Process class provides methods for performing
input from the process, performing output to the process,
waiting for the process to complete, checking the exit status of
the process, and destroying (killing) the process.
Class declaration
Following is the declaration for java.lang.Process class:
public abstract class Process
extends Object
10. Java.lang.ProcessBuilder Class
The java.lang.ProcessBuilder class is used to create
operating system processes.This class is not synchronized.
Class declaration
Following is the declaration
for java.lang.ProcessBuilder class:
public final class ProcessBuilder
extends Object
Java.lang.Runtime Class
The java.lang.Runtime class allows the application to
interface with the environment in which the application is
running.
Class declaration
Following is the declaration for java.lang.Runtime class:
public class Runtime
extends Object
Java.lang.RuntimePermission Class
The java.lang.RuntimePermission class is for runtime
permissions. A RuntimePermission contains a name (also
11. referred to as a "target name") but no actions list; you either
have the named permission or you don't.
Class declaration
Following is the declaration
for java.lang.RuntimePermission class:
public final class RuntimePermission
extends BasicPermission
Java.lang.String Class
The java.lang.String class represents character strings. All
string literals in Java programs, such as "abc", are
implemented as instances of this class.Strings are constant,
their values cannot be changed after they are created
Class declaration
Following is the declaration for java.lang.String class:
public final class String
extends Object
implements Serializable, Comparable<String>,
CharSequence
12. Java.lang.StringBuffer Class
The java.lang.StringBuffer class is a thread-safe, mutable
sequence of characters. Following are the important points
about StringBuffer:
A string buffer is like a String, but can be modified.
It contains some particular sequence of characters, but
the length and content of the sequence can be changed
through certain method calls.
They are safe for use by multiple threads.
Every string buffer has a capacity.
Class declaration
Following is the declaration for java.lang.StringBuffer class:
public final class StringBuffer
extends Object
implements Serializable, CharSequence
13. oops:
1)object oriented programming system(oops)
The features related to object oriented programming
system are
1)class/object
2)Encapsulation
3)Abstraction
4)Inheritance
5)polymorpism
class/object:Entire oops metholodogy has been derived
from a single root concept called object.An object is
nothing that really exists in the worldand can be
distiunshed from others.
string name;
int age;
char sex;
It is possible that some object s may have similar
properties and objects .such objects belong to some
category a class.
variables variables
14. name raju
age 25
sex Male
methods methods
talking Talk()
walking walk()
eating eat()
A class is a modeal for creating objects and does not exit
phyisically,An object is actually that exits phyisically,Both
the class and objects contain variable and methods
Class person
//Properties of a person ---variable
string Name;
int age;
//Action done by a person --method
Void talk()
{
}
15. void eat()
{
}
}
encapsulation:The encapsulation is achieved by
combining the methods and attribute into a class.The class
acts like a container.
Int id;
string name;
Encapsulation in java:
class person
{
//Variable _data
private string name;
private int age
//method
public void talk()
{
system.out.println("Hello,I am "+name);
system.out.println("my age is "+age);
16. }
}
abastraction:There me be a lot af data a class contains and
the user does not need the entire data.The user requires
only some part of the available data. In these case ,we can
hide the unnecessary data from the user and expose only
the data is of interest to the user .This is called abstraction
Eg:Class bank
{
Privcate int accno;
private string name;
private float balance;
private float profit;
private float loan;
Public void display_to_cleark()
{
System.out.printl=n("aCCNO="+aCCNO);
System.out.printl=n("NAME="+name);
System.out.printl=n("balance="+balance);
}
17. }
Inheritance:Inheritance is the property whicH Allows a
child class to inherit some properties from its parent class.
class b extends a
{
}
eg:
class a
{
protected int a;
protected int b;
public void method ()
{
}
}
class b extends a
private int c;
public void method 2()
{
}
}
18. polymorphism:
The word polymorphisim came from the greek word ply
means many and morphos means meaning
The ability to define more than one function with the same
name is called as ploymorphism
Class one
{
Void calculate (int x)]
{
system .out .println("square value ="+?(x*x));
}
}
class two extends one
{
void calculate (int x)
system.out.println("cute value="+(x*x*x));
}
}
19. collections:
A collection Framework is a class library to handle goups of
objects collection is a framework implemented in
java.util.package
A collection object or a container object is an object which can
store a group of other objects.
java .util
collection class
collection objects
A group of objects stored in a single collection objects.
Sets: A set represents group of elements arranged just like an
array. The sets will grow dynamically when the elements are
stored into it. A set will not allow duplicate elements. If we try to
20. pass the same element that is already in the set, then it is not
shared into the set.
List:
Lists are like sets ,they store a group of elements, But list
allows duplicate values to be stored.
Queues:
A queues represents arrangement of elements in FIFO(First in
first out) order. This means elements into the queue will be
removed first from the queue.
Maps:
Maps are stored elements in the form of key and value pairs .If
the key value is provided then it is corresponding value can be
obtained of course ,the key should have unique value.
Iterator interface:
Iterator is an interface that contains methods to retrieve the
elements one by one from a collection object. It has 3 methods
21. Boolean has next():The method returns true if the iterator has
more elements.
Element next(): The method returns the next element in the
itetrator.
Void remove: This method removes from the collection the lost
elements returned by the iterator.
List Iterator Interface:
List iterator is an interface that contains methods retrieve the
elements from a collection object ,both in forward and reverse
diretions.
Enumeration interface: This interface is useful to retrieve one
by one elements like the Iterator It has 2 methods
Boolean has more elements():
22. This method tests if the enumeration has any more elements or
not.
Elements next Elements():This returns the next element thats is
avilable in the Enumeration.
Java Exceptions :l
Exception are used in Java to handle errors or any other
exceptional event that occurs in the normal flow of program.
There are several way Exception can occur in Java.
Data provided is not in expected format(eg. int instead of
String).
DB can not connected.
Network connection Lost.
Object is null.
JVM running out of memory is a type of Error which can occur
at runtime.
23. Overloading:
Overloaded method gives you an option to use the same
method name in a class but with different argument.
Overloading Method Rules
There are some rules associated with overloaded method.
Overloaded methods
Must change the argument list
Can change the return type
Can change the access modifier(Broader)
Can declare new or broader checked exception
A method can be overloaded in Class or in SubClass.
Overloading Method Example
1
2
3
//Overloaded method with two argument
public void add(int input1, int input2) {
System.out.println("In method with two argument");
24. 4
5
6
7
8
9
}
//Overloaded method with one argument
public void add(int input1) {
System.out.println("In method with one argument");
}
Java Method Override:
Class inheriting the method from its super class has the option
to override it. Benefit of overriding is the ability to define
behaviour specific to particular class.
Method Overriding Example
1
2
3
4
5
public class ParentClass
{
public void show()
{
System.out.println("Show method of Super class");
25. 6
7
8
9
10
11
12
13
14
15
16
}
}
public class SubClass extends ParentClass
{
//below method is overriding the ParentClass version of
show method
public void show()
{
System.out.println("Show method of Sub class");
}
}
Method Override Rules
Overriding method can not have more restrictive access
modifier than the method being overriden but it can be less.
The argument list must exactly match that of the overriden
method, if they don’t it is more likely that you are
overloading the method.
Return type must be the same as, or subtype of the return
type declared in overriden method in Super class.
26. Overriding method can throw any unchecked
exception(Runtime)but it can throw checked exception
which is broader or new than those declared by the
overriden method but it can not throw fewer or narrow
checked exception.
Final method can not be overriden.
Static methods can not be overriden.
If a method cannot be inherited then it cannot be overriden.
HashMap
HashMap is HashTable based implementation of Map. This is
the reason why interviewer always ask for difference between
HashMap and HashTable. HashMap is mostly equals to
HashTable except below two differences.
1. HashMap is unsynchronized while HashTable is
synchronised. which means hash table can be shared
between multiple threads but hash map cannot be shared.
2. HashMap permits null while HashTable doesn’t.
27. 3. one more diference is that because of threads safety and
synchronization hash Table is mush slower than hash map
if used in single thread
Example of HashMap
1. How to iterate a Map
2. Different ways of iterating a Map
3. When HashCode and Equals will get called. (Pay close
attention to output of HashCode and equals method call)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
public class HashMapExample {
public static void main(String[] args) {
Map<JBT, Integer> m1 = new HashMap<JBT, Integer>();
JBT t1 = new JBT(1, 2);
JBT t2 = new JBT(1, 3);
JBT t3 = new JBT(2, 1);
28. 17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
m1.put(t1, 1);
m1.put(t2, 2);
m1.put(t3, 3);
System.out.println("Addition Done");
/*
* Below you can find 3 different ways to iterate a Map.
Uncomment
* different section and see the different in Output. Pay
attention to
* when Hashcode and Equals is called
*/
/* Set s = m1.entrySet();
for (Iterator i = s.iterator(); i.hasNext();) {
Map.Entry me = (Map.Entry) i.next();
System.out.println(me.getKey() + " : " + me.getValue());
}
*/
/* for (Map.Entry<JBT, Integer> entry :
m1.entrySet()) {
System.out.println("Key : " + entry.getKey() + " Value : "
+ entry.getValue());
}
*/
for (Object key : m1.keySet()) {
System.out.println("Key : " + key.toString() + " Value : "
+ m1.get(key));
}
}
}
class JBT {
JBT(int i, int j) {
this.i = i;
this.j = j;
29. 54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
}
int i, j;
@Override
public int hashCode() {
System.out.println("Inside HashCode Method");
int k = i + j;
return k;
}
@Override
public boolean equals(Object obj) {
System.out.println("Inside Equals Method");
if (i == ((JBT) obj).i && j == ((JBT) obj).j)
return true;
else
return false;
}
@Override
public String toString() {
return String.valueOf(i).concat(String.valueOf(j));
}
}
Java Hashtable class
o A Hashtable is an array of list.Each list is known as a
bucket.The position of bucket is identified by calling the
hashcode() method.A Hashtable contains values based on
the key. It implements the Map interface and extends
Dictionary class.
o It contains only unique elements.
o It may have not have any null key or value.
30. o It is synchronized.
Example of Hashtable:
1. import java.util.*;
2. class TestCollection16{
3. public static void main(String args[]){
4.
5. Hashtable<Integer,String> hm=new Hashtable<Integer,String
>();
6.
7. hm.put(100,"Amit");
8. hm.put(102,"Ravi");
9. hm.put(101,"Vijay");
10. hm.put(103,"Rahul");
11.
12. for(Map.Entry m:hm.entrySet()){
13. System.out.println(m.getKey()+" "+m.getValue());
14. }
15. }
16.
17. Output:103 Rahul
18. 102 Ravi
19. 101 Vijay
20. 100 Amit
What is Serialization
Serialization is a process in which current state of Object will be
saved in stream of bytes. As byte stream create is platform
31. neutral hence once objects created in one system can be
deserialized in other platform.
What is the use of Serialization
As written above serialization will translate the Object state to
Byte Streams. This B
yte stream can be used for different purpose.
Write to Disk
Store in Memory
Sent byte stream to other platform over network
Save byte stream in DB(As BLOB)
Serialization and Deserialization in Java
Now we know what is serialization. But in terms of Java how
this serialization will work and how to make a class serializable.
Java has already provided out of the box
way(java.io.Serializable Interface) to serialize an Object. If you
32. want any class to be serialized then that class needs to
implement give interface.
Note*: Serializable Interface is a Marker Interface. Hence there
is no method in Serializable interface.
Code for Serialization of Java Class
Employee.java
1
2
3
4
5
6
7
8
9
10
11
12
package com.jbt;
import java.io.Serializable;
public class Employee implements Serializable
{
public String firstName;
public String lastName;
private static final long serialVersionUID = 5462223600l;
}
33. SerializaitonClass.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
package com.jbt;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
public class SerializaitonClass {
public static void main(String[] args) {
Employee emp = new Employee();
emp.firstName = "Vivekanand";
emp.lastName = "Gautam";
try {
FileOutputStream fileOut = new
FileOutputStream("./employee.txt");
ObjectOutputStream out = new
ObjectOutputStream(fileOut);
out.writeObject(emp);
out.close();
fileOut.close();
System.out.printf("Serialized data is saved in ./employee.txt
file");
} catch (IOException i) {
i.printStackTrace();
}
}
}
DeserializationClass.java
34. 1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
package com.jbt;
import java.io.*;
public class DeserializationClass {
public static void main(String[] args) {
Employee emp = null;
try {
FileInputStream fileIn = new
FileInputStream("./employee.txt");
ObjectInputStream in = new ObjectInputStream(fileIn);
emp = (Employee) in.readObject();
in.close();
fileIn.close();
} catch (IOException i) {
i.printStackTrace();
return;
} catch (ClassNotFoundException c) {
System.out.println("Employee class not found");
c.printStackTrace();
return;
}
System.out.println("Deserializing Employee...");
System.out.println("First Name of Employee: " +
emp.firstName);
System.out.println("Last Name of Employee: " +
emp.lastName);
}
}
First run “SerializaitonClass” and you will get “employee.txt”
file created.
35. Second run “DeserializationClass” and java will deserialize
the class and value will be printed in console.
Output would be
1
2
3
4
5
Deserializing Employee...
First Name of Employee: Vivekanand
Last Name of Employee: Gautam
Java Interface
Creating an Interface means defining a Contract. This Contract
states what a class can do without forcing how it should do.
Declaring an Interface
Interface can be defined with Interface keyword.
36. Java Interface Example
1
2
3
4
5
6
7
public interface MyInterface
{
int i=0;
public void Height(int height);
public abstract void setHeight();
}
Rules for Declaring Interface
There are some rules that needs to be followed by Interface.
All Interface methods are implicitly public and abstract. Even
if you write these keyword it will not create problem as you
can see in second method declaration.
Interfaces can declare only Constant. Instance variables are
not allowed. It means all variables inside Interface must be
public, static, final. Variables inside interface are implicitly
public static final.
37. Interface methods can not be static.
Interface methods can not be final, strictfp or native.
Interface can extend one or more other interface. Note:
Interface can only extend other interface.
Interface vs Abstract Class
Interface are like 100% Abstract Class. Interface can not
have non abstract methods while abstract class can have. A
Class Can implement more than one interface while Class can
extend only one class. As Abstract class comes in hierarchy of
Classes it can extend other classes too while Interface can only
extend Interfaces.
Use Interface in Class
How can we take the advantage of Interface after creating it in
Java. To take the advantage we need to implement or class
38. with given Interface. Implement keyword can be used for this
purpose.
Examples of Class Implementing Interface
Example 1:
1
2
3
4
5
6
7
public class InterfaceExampleOne implements interfaceOne {
}
interface interfaceOne {
}
Example 2:
1
2
3
4
/*
* As implmeneted Interface have any abstract method so
this class
* need to implement any method.
*/
39. 5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
class InterfaceExampleTwo implements interfaceTwo {
@Override
public void methhod() {
System.out.println(var);
}
}
/*
* Below interface has an abstract method so implemented
class needs to
* implement this method unless and untill it is abstract itself
*/
interface interfaceTwo {
public final int var = 9;
public abstract void methhod();
}
Example 3:
1
/*
* As below class is not abstract class and it is extending
40. 2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
abstract class which
* has not yet implemented the method from interface so this
class is FORCED to
* implement method from Interface in
hierarachy(interfaceTwo).
*/
class InterfaceExampleTwo extends InterfaceExampleThree
{
@Override
public void methhod() {
System.out.println(var);
}
}
/*
* Below interface has an abstract method so implemented
class needs to
* implement this method unless and untill it is abstract itself
*/
interface interfaceTwo {
public final int var = 9;
41. 24
25
26
27
28
29
30
31
32
33
34
public abstract void methhod();
}
/*
* Even if Interface has abstract method ABSTRACT CLASS
is not forced to
* implement it. Abstract class may/may not navigate this
responsibility of
* implementing abstract method to class which is not
abstract.
*/
abstract class InterfaceExampleThree implements
interfaceTwo {
// Method from Interface is not implemented here
}
Java Thread :
Thread term can be used in two ways
An instance of class java.lang.Thread
42. A Thread of Execution
An Instance of Thread is an object like any other object in Java,
it contains variables and methods which lives and dies on the
heap. But a Thread of Execution is an individual process which
has its ownstack call. Even if you don’t create any thread in
your program, thread will be running there and main() method
will start that.
Note: In case of thread most of thing is unpredictable.
Type of Thread
Thread can be of two types.
User Thread
Daemon Thread
Difference between these two type of thread is that JVM exit an
application only when all User Thread are complete. JVM
doesn’t care about the status of Daemon Thread.
43. Thread Definition
A thread can be defined in two ways
Extend the java.lang.Thread class.
Implement the Runnable interface.
Extending Java Thread class:
Class need to extend the Thread class & Override the
run()method.
1
2
3
4
5
6
7
class MyThread extends Thread
{
public void run()
{
System.out.println("Important job running in MyThread");
}
}
But the problem with this approach is that class can not extend
any more class.
44. Note : run method can be overloaded in class. but only run()
method(without argument) will be consider by JVM. Any other
overridden method will needs to be called explicitly.
Implements runnnable interface
Class needs to implement runnable interface and override the
run() method. Creating Thread in this way gives you flexibility
to extend any class you like.
1
2
3
4
5
6
7
class MyRunnable implements Runnable {
public void run() {
System.out.println("Important job running in MyRunnable");
} }
Instantiating Thread :
Every thread of execution begins as an instance of class
Thread. In any case Thread objects needs to be created before
creating Thread of Execution.
Creating Thread object is different for both the cases. In case of
45. Extending Thread class you can directly initiate class with new
keyword as it has extended Thread class itself.
1 MyThread t = new MyThread()
In case of implimenting Runnable interface. First created
runnable class needs to be instatiated.
1 MyRunnable r = new MyRunnable();
Now pass this runnable object to Thread.
1 Thread t = new Thread(r);
If you create a thread using the no-arg constructor, the thread
will call its own run(). This happened in first case(Extending
Thread class) But in case of Runnable Thread class needs to
know that run method from class implementing runnnable
interface needs to be invoked instead of run() from Thread
class. So we need to pass the class as argument to Thread.
Single runnable instance can be passed to multiple Thread
object.
1
2
public class TestThreads {
46. 3
4
5
6
7
8
9
10
11
12
public static void main (String [] args) {
MyRunnable r = new MyRunnable();
Thread foo = new Thread(r);
Thread bar = new Thread(r);
Thread bat = new Thread(r);
}}
Giving the same target to multiple threads means that several
threads of execution will be running the very same job (and that
the same job will be done multiple times).
Note : The Thread class itself implements Runnable. (After all,
it has a run() method that we were overriding.) This means that
you could pass a Thread to another Thread’s constructor.
Overloaded constructor in Thread class:
1
2
Thread()
Thread(Runnable target)
47. 3
4
Thread(Runnable target, String name)
Thread(String name)
Till now we have created Thread object and it knows what to do
in form of run() method. But till now it is still an object. It does
not have its own call stack. In other words Thread of execution
has not been started. A Thread object will have its own stack
only when start() method will be called on Thread.
Till now Thread has 2 states.
New state (Thread object created but Start method not
invoked)
runnable(alive) state (start method is invoked )
Note : Calling run() method from java code directly mean that
you are invoking a method and stack will not be created.
When a Thread is in runnable state means Thread is created
but it’s run method is not yet executed and thread is waiting for
his turn. Once Thread got selected thread’s run method will
execute and that state will called running state.
48. Thread Scheduler :
The thread scheduler is the part of the JVM that decides which
thread should run at any given moment, and also takes threads
out of the run state. Any thread in the runnable state can be
chosen by the scheduler to be the one and only running thread.
If a thread is not in a runnable state, then it cannot be chosen
to be the currently running thread. Some method that can
influence scheduler to some extent(Note*: We can’t control the
behavior of Thread scheduler)
These methods are from Thread class
1
2
3
4
* public static void sleep(long millis) throws
InterruptedException
* public static void yield()
* public final void join() throws InterruptedException
* public final void setPriority(int newPriority)
Methods from Object class.
1
2
3
* public final void wait() throws InterruptedException
* public final void notify()
* public final void notifyAll()
49. Till now we come across 3 state of Thread
New
Runnable
Running
There are some more state of thread in which Thread will not
be eligible to run.
Waiting/blocked/sleeping
Dead
A thread is in Dead state when its run method completed its
execution.
Sleeping
The sleep() method is a static method of class Thread. (where
it still has to beg to be the currently running thread). as it is
static method only currently running Thread will sleep. Syntax
would be : Thread.sleep()
yield: yield method is related with the priority of Thread. It is
also static method so it works only on currently running thread.
50. Scheduler make it sure that If a thread enters the runnable
state, and it has a higher priority than any of the threads in the
pool and a higher priority than the currently running thread, the
lower-priority running thread usually will be bumped back to
runnable and the highest-priority thread will be chosen to run.
at any given time the currently running thread usually will not
have a priority that is lower than any of the threads in the pool.
yield() is supposed to do is make the currently running thread
head back to runnable to allow other threads of the same
priority to get their turn.
Join()
Join is a non static method. It lets one thread “join onto the end”
of another thread. If you join Thread B to Thread A Thread B
will not start untill Thread A complets.
Syntax :
1
2
3
Thread t = new Thread();
t.start();
t.join();
51. takes the currently running thread and joins it to the end of the
thread referenced by t
There are several other way in which Thread can leave running
state and can return to Runnable state. run methods completes
a call to wait()
Synchronize: It works with Lock. Lock is of two type.
Static lock
Non static lock
Note: There is only one lock per object. Once a thread got the
lock of an object no other thread can enter the synchronise
block/method of given object.
Only methods/block can be synchronised not variable or class.
A class can have both synchronised / non synchronised
method.
Thread can access non synchronised block even if one Thread
got the lock of give object.
52. If a thread goes to sleep, it holds any locks it has. A thread can
have Lock of different object at the same time.
Syntax :
1
2
3
4
5
6
7
8
9
10
11
class SyncTest {
public void doStuff() {
System.out.println("not synchronized");
synchronized(this) {
System.out.println("synchronized");
}}}
Synchronised Static method :
There is only one copy of the static data, so you only need one
lock per class to synchronize static methods—a lock for the
whole class. There is such a lock; every class loaded in Java
has a corresponding instance of java.lang.Class representing
53. that class. It’s that java.lang.Class instance whose lock is used
to protect the static methods of the class.
Syntax:
1
2
3
4
5
public static synchronized int getCount() {
return count;
}
MyClass.class thing is called a class literal. It tells the compiler
(who tells the JVM): go and find me the instance of Class that
represents the class called MyClass.
Note : Threads calling non-static synchronized methods in the
same class will only block each other if they’re invoked using
the same instance. As there is only one lock per instance.
Threads calling static synchronized methods in the same class
will always block each other— As there is only one lock per
class.
54. A static synchronized method and a non-static synchronized
method will not block each other. As they need lock for different
thing(Object & class)
Note : join(), sleep(), yield() these methods keep locks. while
wait release Lock.
What are mutable objects and immutable objects?
An Immutable object is a kind of object whose state cannot be
modified after it is created. This is as opposed to a mutable
object, which can be modified after it is created.
In Java, objects are referred by references. If an object is
known to be immutable, the object reference can be shared.
For
example, Boolean, Byte, Character, Double, Float, Integer,Lo
ng, Short, and String are immutable classes in Java, but the
class StringBuffer is a mutable object in addition to the
immutable String.
class Program {
public static void main(String[] args) {
String str = "HELLO";
System.out.println(str);
str.toLower();
System.out.println(str);
}
}
The output result is
HELLO
HELLO
55. From the above example, the toLower() method does not
impact on the original content in str. What happens is that a
new String object "hello" is constructed. The toLower() method
returns the new constructed String object's reference. Let's
modify the above code:
class Program {
public static void main(String[] args) {
String str = "HELLO";
System.out.println(str);
String str1 = str.toLower();
System.out.println(str1);
}
}
The output result is
HELLO
hello
The str1 references a new String object that contains "hello".
The String object's method never affects the data the String
object contains, excluding the constructor.
"Classes should be immutable unless there's a very good
reason to make them mutable....If a class cannot be made
immutable, you should still limit its mutability as much as
possible."