This is my attempt to compose a brief and cursory introduction to concepts in Java programming language. I call it Java Quicky.
I plan to extend and enhance it over time.
This document discusses inter-thread communication methods like wait() and notify() that allow threads to synchronize access to shared resources. It describes the producer-consumer problem that can occur when threads access a shared buffer without synchronization. It provides examples of incorrect and correct implementations of the producer-consumer pattern using wait(), notify(), and synchronization to allow a producer thread to add items to a buffer while a consumer thread removes items.
Inter thread communication & runnable interfacekeval_thummar
Inter-thread communication allows threads to pause execution in critical sections and allow other threads to enter those sections. It uses the wait(), notify(), and notifyAll() methods of the Object class. wait() pauses a thread until another calls notify() or notifyAll(), notify() wakes one waiting thread, and notifyAll() wakes all waiting threads. The Runnable interface provides a common protocol for objects to execute code while active. To create a thread using Runnable, a class implements Runnable and defines a run() method, a Thread object is created passing the Runnable, and start() is called to execute run().
This document provides an introduction to concurrency in Java programming. It discusses modifying a word counting program to run in parallel using threads. It covers thread safety, critical sections, synchronized blocks and methods, lock objects, and other concurrency concepts in Java like volatile fields and deadlocks. The document uses examples to illustrate how to design thread-safe classes and properly synchronize access to shared resources between multiple threads.
This document discusses effective practices for overriding common object methods like equals, hashCode, toString, and clone in Java. It provides guidelines on when each method should be overridden to obey general contracts and ensure proper functioning with collections and other classes. Key points covered include always overriding equals and hashCode together, following specific rules when overriding equals, and cloning objects judiciously by implementing Cloneable and providing either shallow or deep copies.
The document discusses several key concepts in object-oriented programming including encapsulation, abstraction, inheritance, polymorphism, and relationships between classes like HAS-A. It also covers topics like garbage collection in Java, the heap memory structure, and common Java Virtual Machine switches for configuring memory.
Java concurrency allows applications to make use of multiple processors and handle asynchronous operations through the use of threads. While concurrency provides benefits like improved performance, it also introduces risks like race conditions and deadlocks if threads access shared resources unsafely. The Java threading APIs provide tools for safely managing concurrent operations through mechanisms like synchronization, locks, and concurrent collections.
This document provides an overview of the Java programming language. It discusses key features such as platform independence, object-oriented programming principles like inheritance and polymorphism, automatic memory management, and security features. It also covers basic Java concepts like primitive data types, variables, operators, flow control statements, methods, and classes.
This document discusses inter-thread communication methods like wait() and notify() that allow threads to synchronize access to shared resources. It describes the producer-consumer problem that can occur when threads access a shared buffer without synchronization. It provides examples of incorrect and correct implementations of the producer-consumer pattern using wait(), notify(), and synchronization to allow a producer thread to add items to a buffer while a consumer thread removes items.
Inter thread communication & runnable interfacekeval_thummar
Inter-thread communication allows threads to pause execution in critical sections and allow other threads to enter those sections. It uses the wait(), notify(), and notifyAll() methods of the Object class. wait() pauses a thread until another calls notify() or notifyAll(), notify() wakes one waiting thread, and notifyAll() wakes all waiting threads. The Runnable interface provides a common protocol for objects to execute code while active. To create a thread using Runnable, a class implements Runnable and defines a run() method, a Thread object is created passing the Runnable, and start() is called to execute run().
This document provides an introduction to concurrency in Java programming. It discusses modifying a word counting program to run in parallel using threads. It covers thread safety, critical sections, synchronized blocks and methods, lock objects, and other concurrency concepts in Java like volatile fields and deadlocks. The document uses examples to illustrate how to design thread-safe classes and properly synchronize access to shared resources between multiple threads.
This document discusses effective practices for overriding common object methods like equals, hashCode, toString, and clone in Java. It provides guidelines on when each method should be overridden to obey general contracts and ensure proper functioning with collections and other classes. Key points covered include always overriding equals and hashCode together, following specific rules when overriding equals, and cloning objects judiciously by implementing Cloneable and providing either shallow or deep copies.
The document discusses several key concepts in object-oriented programming including encapsulation, abstraction, inheritance, polymorphism, and relationships between classes like HAS-A. It also covers topics like garbage collection in Java, the heap memory structure, and common Java Virtual Machine switches for configuring memory.
Java concurrency allows applications to make use of multiple processors and handle asynchronous operations through the use of threads. While concurrency provides benefits like improved performance, it also introduces risks like race conditions and deadlocks if threads access shared resources unsafely. The Java threading APIs provide tools for safely managing concurrent operations through mechanisms like synchronization, locks, and concurrent collections.
This document provides an overview of the Java programming language. It discusses key features such as platform independence, object-oriented programming principles like inheritance and polymorphism, automatic memory management, and security features. It also covers basic Java concepts like primitive data types, variables, operators, flow control statements, methods, and classes.
This document discusses Java bytecode manipulation techniques using unsafe, instrumentation, and Java agents. It covers areas where bytecode manipulation is commonly used like mocking, persistence, and security. It analyzes techniques for defining and transforming classes at runtime and discusses challenges like injecting state and working with modules. The document also proposes ideas to standardize testing support and provide a unified dynamic code generation concept in Java.
- Java is a platform independent programming language that is similar to C++ in syntax but similar to Smalltalk in its object-oriented approach. It provides features like automatic memory management, security, and multi-threading capabilities.
- Java code is compiled to bytecode that can run on any Java Virtual Machine (JVM). The JVM then interprets the bytecode and may perform just-in-time (JIT) compilation for improved performance. This allows Java programs to run on any platform with a JVM.
- Java supports object-oriented programming principles like encapsulation, inheritance, and polymorphism. Classes can contain methods and instance variables. Methods can be called on objects to perform operations or retrieve data.
- Java is a platform independent programming language that is similar to C++ in syntax but similar to Smalltalk in its object-oriented approach. It provides features like automatic memory management, security, and multi-threading capabilities.
- Java code is compiled to bytecode that can run on any Java Virtual Machine (JVM). Only depending on the JVM allows Java code to run on any hardware or operating system with a JVM.
- Java supports object-oriented programming concepts like inheritance, polymorphism, and encapsulation. Classes can contain methods and instance variables. Methods perform actions and can return values.
Java Serialization is often considered a dark art of Java programmers. This session will lift the veil and show what serialization is and isn't, how you can use it for profit and evil. After this session no NotSerializableException will be unconquerable.
This document provides an introduction to learning Java, including:
- An overview of Java as an object-oriented language developed by Sun Microsystems, featuring a virtual machine, portability, and memory management.
- Instructions for compiling and running a simple "Hello World" Java program from the command line.
- Explanations of Java programming basics like classes, methods, variables, operators, and control structures.
The document discusses Java 5 concurrency features including locks, conditions, atomic variables, blocking queues, concurrent hash maps, synchronizers like semaphores and mutexes, and the executor framework. Key points include:
- Locks provide an alternative to synchronized blocks and methods, and allow more flexible locking behavior. ReentrantLock is a common lock implementation.
- Conditions (condition variables) allow threads to wait/signal and are used with locks rather than synchronized monitors.
- Atomic variables ensure thread-safe operations on single variables without locking.
The document discusses various string methods in Java. It explains concepts like autoboxing, unboxing, string comparison using equals(), ==, compareTo() methods. It also discusses substring, concatenation using concat(), uppercasing/lowercasing using toUpperCase(), toLowerCase() methods. Common string methods like trim(), length(), charAt(), startsWith(), endsWith() are also explained along with examples.
Java agents and their instrumentation API offer developers the most powerful toolset to interact with a Java application. Using this API, it becomes possible to alter the code of running applications, for example to add monitoring or to inject security checks as it is done by many enterprise products for the Java ecosystem.
In this session, developers will learn how to program Java agents of their own that make use of the instrumentation API. Doing so, developers learn how the majority of tooling for the JVM is implemented and will learn about Byte Buddy, a high level code generation library that does not require any knowledge of Java byte code that is normally required for writing agents. In the process, developers will see how Java classes can be used as templates for implementing highly performant code changes that avoid the boilerplate of alternative solutions such as AspectJ or Javassist while still performing better than agents implemented in low-level libraries such as ASM.
This document discusses concepts related to threads and concurrency in Java. It begins by defining processes and threads, explaining that processes contain threads. It then covers key threading concepts like thread pools, synchronization, and data management between threads. The document provides examples of why threads are used and best practices for writing threaded code in Java. It also discusses common threading issues like deadlocks and race conditions and how to avoid them.
Lara Technologies are providing Software Training Division, Java/J2ee, Android, Web Services, Logical Coding, Basics Of C Language, Soft Skills, Aptitude, Etc.
Deadlocks occur when threads mutually block each other by holding resources the other needs. An example program demonstrates deadlock by having two threads call synchronized methods on separate objects that each pause briefly before calling a method on the other object. To avoid deadlock, resources should be requested in the same order by all threads or code within synchronized blocks should not halt thread execution.
This document discusses the java.util.StringTokenizer class which allows breaking a string into tokens. It describes the constructors and methods of StringTokenizer, including how to count, check for, and retrieve the next token. An example program demonstrates its use by tokenizing a sample string and outputting the results.
This document provides an overview of how to create test classes and methods in JUnit and mock objects using frameworks like PowerMock and EasyMock. It describes how to define a test class that extends TestCase and overrides setUp(), tearDown(), and testXXX() methods. It also explains how PowerMock allows mocking static methods, private methods, final classes/methods by using annotations and bytecode manipulation.
Demonstrate some great aspects of Mockito. Made for Mockito v1.8.5.
All examples can be found @
https://github.com/dodozhang21/MockitoExamples
Ying Zhang (Dodo) http://pure-essence.net
The document discusses multithreading and threading concepts in Java. It defines a thread as a single sequential flow of execution within a program. Multithreading allows executing multiple threads simultaneously by sharing the resources of a process. The key benefits of multithreading include proper utilization of resources, decreased maintenance costs, and improved performance of complex applications. Threads have various states like new, runnable, running, blocked, and dead during their lifecycle. The document also explains different threading methods like start(), run(), sleep(), yield(), join(), wait(), notify() etc and synchronization techniques in multithreading.
This document discusses several core Java concepts including comments, classes, objects, scopes, static methods and fields, arrays, and constructors. It provides examples of Java code for classes, methods, and constructors. Key points covered include: javadoc comments generate API documentation; classes describe data and operations on objects; scopes are determined by curly braces; static methods and fields belong to the class not instances; arrays are objects that can be dynamically allocated; and constructors create class instances and invoke superclass constructors.
This talk was given in ilJUG on the 29th of July 2014 and discusses the new Java8 StampedLock class. It compares it to different locking mechanism is Java and shows some insights deduced from a simple benchmark
This document discusses autoboxing and unboxing in Java. It explains that autoboxing allows primitive data types to be automatically wrapped into their corresponding wrapper classes when used where an object is expected. Unboxing is the reverse process where the primitive value is automatically extracted from the wrapper class. This simplifies coding by eliminating the need to manually wrap and unwrap values. Autoboxing and unboxing was introduced in Java 5 to make programming with primitive types and wrapper classes more convenient.
Qualysoft's Best Online Offer Methodology for insurance companies with digita...Ilona Anna Szabo, MBA
Selling an insurance product online
Provide a humanized digital customer experience for your visitors getting a quote:
- enhance and optimize customer experience by control over and improving the multichannel sales process with the help of IT applying state of the art technologies and solutions
- individualized and interactive processes (channel of preference, support transmission seamlessly between channels, sessions; real-time intervention, ..)
- offer properly customized and personalized recommendations (product recommendations, personalized features, ..)
Answer for additional customer griefs, as Qualysoft is suggesting it in its BOOM solution:
- Ease of completing the transaction
- Capture both quantitative and qualitative details of visitors’ every single website interaction
- Capitalize on data: analyze, segment, predict, target
- Capture (replay) and enhance website visitor’s (both customer site and agent / broker site) complete user experience by answering the „why” questions 1.
- Website optimization on conversion, straightforward navigation, real time interactions
- Marketing automation
- Integrate a personal advisor if required
Capture more leads, have more efficient sales, increase profits
This document discusses Java bytecode manipulation techniques using unsafe, instrumentation, and Java agents. It covers areas where bytecode manipulation is commonly used like mocking, persistence, and security. It analyzes techniques for defining and transforming classes at runtime and discusses challenges like injecting state and working with modules. The document also proposes ideas to standardize testing support and provide a unified dynamic code generation concept in Java.
- Java is a platform independent programming language that is similar to C++ in syntax but similar to Smalltalk in its object-oriented approach. It provides features like automatic memory management, security, and multi-threading capabilities.
- Java code is compiled to bytecode that can run on any Java Virtual Machine (JVM). The JVM then interprets the bytecode and may perform just-in-time (JIT) compilation for improved performance. This allows Java programs to run on any platform with a JVM.
- Java supports object-oriented programming principles like encapsulation, inheritance, and polymorphism. Classes can contain methods and instance variables. Methods can be called on objects to perform operations or retrieve data.
- Java is a platform independent programming language that is similar to C++ in syntax but similar to Smalltalk in its object-oriented approach. It provides features like automatic memory management, security, and multi-threading capabilities.
- Java code is compiled to bytecode that can run on any Java Virtual Machine (JVM). Only depending on the JVM allows Java code to run on any hardware or operating system with a JVM.
- Java supports object-oriented programming concepts like inheritance, polymorphism, and encapsulation. Classes can contain methods and instance variables. Methods perform actions and can return values.
Java Serialization is often considered a dark art of Java programmers. This session will lift the veil and show what serialization is and isn't, how you can use it for profit and evil. After this session no NotSerializableException will be unconquerable.
This document provides an introduction to learning Java, including:
- An overview of Java as an object-oriented language developed by Sun Microsystems, featuring a virtual machine, portability, and memory management.
- Instructions for compiling and running a simple "Hello World" Java program from the command line.
- Explanations of Java programming basics like classes, methods, variables, operators, and control structures.
The document discusses Java 5 concurrency features including locks, conditions, atomic variables, blocking queues, concurrent hash maps, synchronizers like semaphores and mutexes, and the executor framework. Key points include:
- Locks provide an alternative to synchronized blocks and methods, and allow more flexible locking behavior. ReentrantLock is a common lock implementation.
- Conditions (condition variables) allow threads to wait/signal and are used with locks rather than synchronized monitors.
- Atomic variables ensure thread-safe operations on single variables without locking.
The document discusses various string methods in Java. It explains concepts like autoboxing, unboxing, string comparison using equals(), ==, compareTo() methods. It also discusses substring, concatenation using concat(), uppercasing/lowercasing using toUpperCase(), toLowerCase() methods. Common string methods like trim(), length(), charAt(), startsWith(), endsWith() are also explained along with examples.
Java agents and their instrumentation API offer developers the most powerful toolset to interact with a Java application. Using this API, it becomes possible to alter the code of running applications, for example to add monitoring or to inject security checks as it is done by many enterprise products for the Java ecosystem.
In this session, developers will learn how to program Java agents of their own that make use of the instrumentation API. Doing so, developers learn how the majority of tooling for the JVM is implemented and will learn about Byte Buddy, a high level code generation library that does not require any knowledge of Java byte code that is normally required for writing agents. In the process, developers will see how Java classes can be used as templates for implementing highly performant code changes that avoid the boilerplate of alternative solutions such as AspectJ or Javassist while still performing better than agents implemented in low-level libraries such as ASM.
This document discusses concepts related to threads and concurrency in Java. It begins by defining processes and threads, explaining that processes contain threads. It then covers key threading concepts like thread pools, synchronization, and data management between threads. The document provides examples of why threads are used and best practices for writing threaded code in Java. It also discusses common threading issues like deadlocks and race conditions and how to avoid them.
Lara Technologies are providing Software Training Division, Java/J2ee, Android, Web Services, Logical Coding, Basics Of C Language, Soft Skills, Aptitude, Etc.
Deadlocks occur when threads mutually block each other by holding resources the other needs. An example program demonstrates deadlock by having two threads call synchronized methods on separate objects that each pause briefly before calling a method on the other object. To avoid deadlock, resources should be requested in the same order by all threads or code within synchronized blocks should not halt thread execution.
This document discusses the java.util.StringTokenizer class which allows breaking a string into tokens. It describes the constructors and methods of StringTokenizer, including how to count, check for, and retrieve the next token. An example program demonstrates its use by tokenizing a sample string and outputting the results.
This document provides an overview of how to create test classes and methods in JUnit and mock objects using frameworks like PowerMock and EasyMock. It describes how to define a test class that extends TestCase and overrides setUp(), tearDown(), and testXXX() methods. It also explains how PowerMock allows mocking static methods, private methods, final classes/methods by using annotations and bytecode manipulation.
Demonstrate some great aspects of Mockito. Made for Mockito v1.8.5.
All examples can be found @
https://github.com/dodozhang21/MockitoExamples
Ying Zhang (Dodo) http://pure-essence.net
The document discusses multithreading and threading concepts in Java. It defines a thread as a single sequential flow of execution within a program. Multithreading allows executing multiple threads simultaneously by sharing the resources of a process. The key benefits of multithreading include proper utilization of resources, decreased maintenance costs, and improved performance of complex applications. Threads have various states like new, runnable, running, blocked, and dead during their lifecycle. The document also explains different threading methods like start(), run(), sleep(), yield(), join(), wait(), notify() etc and synchronization techniques in multithreading.
This document discusses several core Java concepts including comments, classes, objects, scopes, static methods and fields, arrays, and constructors. It provides examples of Java code for classes, methods, and constructors. Key points covered include: javadoc comments generate API documentation; classes describe data and operations on objects; scopes are determined by curly braces; static methods and fields belong to the class not instances; arrays are objects that can be dynamically allocated; and constructors create class instances and invoke superclass constructors.
This talk was given in ilJUG on the 29th of July 2014 and discusses the new Java8 StampedLock class. It compares it to different locking mechanism is Java and shows some insights deduced from a simple benchmark
This document discusses autoboxing and unboxing in Java. It explains that autoboxing allows primitive data types to be automatically wrapped into their corresponding wrapper classes when used where an object is expected. Unboxing is the reverse process where the primitive value is automatically extracted from the wrapper class. This simplifies coding by eliminating the need to manually wrap and unwrap values. Autoboxing and unboxing was introduced in Java 5 to make programming with primitive types and wrapper classes more convenient.
Qualysoft's Best Online Offer Methodology for insurance companies with digita...Ilona Anna Szabo, MBA
Selling an insurance product online
Provide a humanized digital customer experience for your visitors getting a quote:
- enhance and optimize customer experience by control over and improving the multichannel sales process with the help of IT applying state of the art technologies and solutions
- individualized and interactive processes (channel of preference, support transmission seamlessly between channels, sessions; real-time intervention, ..)
- offer properly customized and personalized recommendations (product recommendations, personalized features, ..)
Answer for additional customer griefs, as Qualysoft is suggesting it in its BOOM solution:
- Ease of completing the transaction
- Capture both quantitative and qualitative details of visitors’ every single website interaction
- Capitalize on data: analyze, segment, predict, target
- Capture (replay) and enhance website visitor’s (both customer site and agent / broker site) complete user experience by answering the „why” questions 1.
- Website optimization on conversion, straightforward navigation, real time interactions
- Marketing automation
- Integrate a personal advisor if required
Capture more leads, have more efficient sales, increase profits
The document discusses challenges with traditional mobile advertising like poor user experience and accidental clicks. It introduces new hyper-rich media ad units from Beintoo that aim to be more engaging for users. Three new units are described: InGame Rewards that integrate into mobile games seamlessly; GameDrop which allows users to interact with ads within apps without leaving; and NavMe which gamifies location-based missions to stores to increase awareness and in-store activity. The goal is to deliver higher consumer engagement and value for advertisers than traditional mobile ads.
This is my first publication on concepts of the C++ programming language. I also discuss high level ideas in software architecture and Design Patterns.
Enjoy and like it!
Stay tuned for more.
Este documento presenta el caso de Santiago Guzmán, un niño de 6 años que presenta deficiencias en el lenguaje y las matemáticas. Se le aplicó el Test ABC para evaluar su madurez para la lectoescritura, obteniendo una puntuación baja de 7 puntos que indica un nivel de maduración inferior. Adicionalmente, se realizó un test de Token a dos pacientes adultos mayores para evaluar su capacidad de análisis y comprensión.
El documento presenta una discusión entre Erick y Carlos sobre una carta de recomendación laboral. Erick le pide a Carlos que le dé una carta, pero Carlos responde que se la pida a su mamá en vez de él. Esto lleva a un malentendido entre los dos amigos. El documento también incluye varios párrafos sobre las posiciones católica y evangélica respecto a María y su devoción.
This presentation describes key concepts in Java. I call it The Java Quicky.
This is part of a series of presentations to cover the Java programming language and its new offerings and versions in depth.
In the publication I briefly describe what metaclasses are in Python. The writeup is a living item and will be extended with more detail shortly.
Please enjoy and comment.
Este documento discute los trastornos de ansiedad y depresión en niños y adolescentes. Explica que estos trastornos han estado aumentando rápidamente sin tratamiento, afectando el desarrollo académico, social y familiar de los niños. El objetivo es analizar las posibles causas y factores que contribuyen a estos trastornos en los niños, así como identificarlos de manera apropiada.
Consumers have limited loyalty to healthcare providers and are open to switching primary care physicians. Younger consumers especially lack loyalty, with over 60% of those aged 18-44 willing to switch. Providers need to develop trust and deliver value through personalized communications and programs that meet consumer needs and preferences in order to build stronger engagement and loyalty. Consumers are looking for convenient access, rewards for healthy behaviors, and guidance on managing costs. Sharing fitness and shopping data with providers could also improve health if used to benefit consumers. However, most consumer engagement currently is limited, through phone contact alone.
This document defines various C++ concepts and terms. It discusses classes, objects, abstraction, encapsulation, overloading, generics, inheritance, polymorphism, templates, dynamic binding, abstract base classes, namespaces, exceptions, containers, the standard template library, function objects, differences between C and C++, references, mutability, initialization lists, casts, CppUnit for testing, and design patterns. It provides brief definitions and examples for each term to explain core C++ concepts and features.
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.
The document provides an overview of several Java topics including class loaders, the Object class, collections, exception handling, and files and I/O. It begins with an agenda and rules for the session. It then discusses class loaders and how they load classes, custom class loaders, and building a simple class loader. Next, it describes the Object class and its common methods. It continues with an overview of collections, interfaces like Collection and Comparator, and the Collections utility class. The document then covers exception handling concepts like checked, unchecked exceptions and errors, and how to catch and handle exceptions. Finally, it discusses Java I/O streams and input/output stream classes.
The Collection API provides classes and interfaces that support operations on collections of objects, such as HashSet, HashMap, ArrayList, and LinkedList. It replaces vectors, arrays, and hashtables. Iterator is an interface used to iterate through elements of a Collection. The differences between an abstract class and interface are that interfaces provide multiple inheritance while abstract classes do not, and interfaces only define public methods without implementation.
The document contains questions and answers related to Java interview questions. It discusses topics like access modifiers, differences between abstract classes and interfaces, garbage collection, constructors vs methods, inheritance, polymorphism, exceptions and more. The questions aim to test the interviewee's understanding of core Java concepts.
Myassignmenthelpers.com is an Online service provider for Java assignments & homework problems. Our online experts provide Java Assignment help & Java homework help with aims to help college students across the globe. Our writers provide you unique data along with a plagiarised report so that you can ensure that your data is unique. Our writers are available 24*7. Please send your complete requirements at support@myassignmenthelpers.com or else attach on the website. You can also discuss the requirements with our chat agent.
1. The document discusses various Java programming concepts like methods, classes, inheritance, method overloading, recursion, access modifiers, static, final, abstract etc.
2. It provides examples to explain method overloading, constructor overloading, recursion, inheritance forms like single, multilevel, hierarchical etc.
3. It also discusses the usage of keywords like final, static, abstract and usage of super keyword in inheritance.
The document discusses key concepts in Object Oriented Programming (OOP) in Java including classes, objects, references, constructors, inheritance, abstraction, polymorphism, and generics. It defines classes as blueprints for objects, and objects as instances of classes that have state and behavior. Constructors are used to initialize new objects. Inheritance and abstraction allow classes to extend and implement other classes and interfaces. Polymorphism enables different classes to implement the same methods in different ways. Generics provide type safety for collections of objects.
The document discusses the internal architecture and execution of the Java Virtual Machine (JVM). It describes how the JVM loads and executes Java bytecode, manages memory areas like the heap and method area, and allows for multithreaded execution through individual call stacks and synchronization between threads. Key components of the JVM include the class loader subsystem, execution engine, runtime data areas, Java stacks, and program counters for each thread.
- Java is a platform independent programming language that is similar to C++ in syntax but similar to Smalltalk in its object-oriented approach. It provides features like automatic memory management, security, and multi-threading capabilities.
- Java code is compiled to bytecode that can run on any Java Virtual Machine (JVM). Only depending on the JVM allows Java code to run on any hardware or operating system with a JVM.
- Java supports object-oriented programming concepts like inheritance, polymorphism, and encapsulation. Classes can contain methods and instance variables to define objects.
Java allows writing code once that can run on any platform. It compiles to bytecode that runs on the Java Virtual Machine (JVM). Key features include automatic memory management, object-oriented design, platform independence, security, and multi-threading. Classes are defined in .java files and compiled to .class files. The JVM interprets bytecode and uses just-in-time compilation to improve performance.
The document discusses various Java concepts including object-oriented principles, inheritance, polymorphism, encapsulation, constructors, methods, exceptions, threads, and memory management. It provides definitions and explanations of key terms like inheritance, polymorphism, method overloading, overriding, checked and unchecked exceptions, static and non-static methods, and the differences between concepts like ArrayList and Vector, and method overloading versus overriding.
Static members in Java include static variables, static blocks, and static methods.
Static variables and blocks are initialized when the class is loaded, while static methods can be accessed without creating an object. Overloading static methods is allowed by having multiple methods with the same name but different parameters. The order of execution is that static variables and blocks are initialized in the order they are declared, followed by the main method.
String is immutable in Java for security and efficiency reasons. Immutability allows strings to be shared and cached without risk of unexpected changes from another thread. The String class is declared final to prevent extension and mutation. Immutable strings enable safe sharing across threads and applications like databases and networking without the risk of data corruption from concurrent modifications.
Java is a platform independent programming language similar to C++ in syntax and Smalltalk in mental paradigm. It has features like automatic type checking, garbage collection, simplified pointers and network access. Java code is compiled to bytecode, which is interpreted by the Java Virtual Machine (JVM) on various platforms, making Java portable across different operating systems and hardware. Methods and data in Java classes can be declared as public or private to control access and eliminate errors between classes.
The document discusses Java packages, interfaces, exceptions, and stack traces. It provides details on:
- How to define and use packages to organize code and control access
- The purpose and features of interfaces like default and static methods
- The different types of exceptions and how to handle exceptions using try/catch blocks
- How stack traces track the location where exceptions occur by providing stack frame details
Java Tutorial
Write Once, Run Anywhere
The document provides an overview of Java including:
- Java is a platform independent programming language similar to C++ in syntax and Smalltalk in mental paradigm.
- Key features of Java include automatic type checking, garbage collection, simplified pointers and network access, and multi-threading.
- Java code is compiled to bytecode, which is interpreted by the Java Virtual Machine (JVM) on any platform, allowing Java to be platform independent. Just-in-time compilers attempt to increase speed.
Polymorphism allows one interface to behave differently depending on the object calling it. It supports method overloading and overriding. The List interface represents collections of objects and its main implementations are ArrayList, Vector, and LinkedList. Constructors initialize newly created objects and are invoked when objects are created. Access specifiers like public, private, protected, and default control object access in Java.
This document provides an overview of the Java programming language. It discusses key features such as platform independence, object-oriented programming principles like inheritance and polymorphism, automatic memory management, and security features. It also covers basic Java concepts like primitive data types, variables, operators, control flow statements, methods, classes and objects.
Java is an object-oriented programming language that is platform independent, allowing code to run on any device. It features automatic memory management, strong typing, and multi-threading. Java code is compiled to bytecode that runs on a Java Virtual Machine, providing platform independence. Methods and classes encapsulate code and data, and inheritance, polymorphism, and interfaces support object-oriented programming.
Preparing Non - Technical Founders for Engaging a Tech AgencyISH Technologies
Preparing non-technical founders before engaging a tech agency is crucial for the success of their projects. It starts with clearly defining their vision and goals, conducting thorough market research, and gaining a basic understanding of relevant technologies. Setting realistic expectations and preparing a detailed project brief are essential steps. Founders should select a tech agency with a proven track record and establish clear communication channels. Additionally, addressing legal and contractual considerations and planning for post-launch support are vital to ensure a smooth and successful collaboration. This preparation empowers non-technical founders to effectively communicate their needs and work seamlessly with their chosen tech agency.Visit our site to get more details about this. Contact us today www.ishtechnologies.com.au
Top Benefits of Using Salesforce Healthcare CRM for Patient Management.pdfVALiNTRY360
Salesforce Healthcare CRM, implemented by VALiNTRY360, revolutionizes patient management by enhancing patient engagement, streamlining administrative processes, and improving care coordination. Its advanced analytics, robust security, and seamless integration with telehealth services ensure that healthcare providers can deliver personalized, efficient, and secure patient care. By automating routine tasks and providing actionable insights, Salesforce Healthcare CRM enables healthcare providers to focus on delivering high-quality care, leading to better patient outcomes and higher satisfaction. VALiNTRY360's expertise ensures a tailored solution that meets the unique needs of any healthcare practice, from small clinics to large hospital systems.
For more info visit us https://valintry360.com/solutions/health-life-sciences
Malibou Pitch Deck For Its €3M Seed Roundsjcobrien
French start-up Malibou raised a €3 million Seed Round to develop its payroll and human resources
management platform for VSEs and SMEs. The financing round was led by investors Breega, Y Combinator, and FCVC.
UI5con 2024 - Keynote: Latest News about UI5 and it’s EcosystemPeter Muessig
Learn about the latest innovations in and around OpenUI5/SAPUI5: UI5 Tooling, UI5 linter, UI5 Web Components, Web Components Integration, UI5 2.x, UI5 GenAI.
Recording:
https://www.youtube.com/live/MSdGLG2zLy8?si=INxBHTqkwHhxV5Ta&t=0
UI5con 2024 - Bring Your Own Design SystemPeter Muessig
How do you combine the OpenUI5/SAPUI5 programming model with a design system that makes its controls available as Web Components? Since OpenUI5/SAPUI5 1.120, the framework supports the integration of any Web Components. This makes it possible, for example, to natively embed own Web Components of your design system which are created with Stencil. The integration embeds the Web Components in a way that they can be used naturally in XMLViews, like with standard UI5 controls, and can be bound with data binding. Learn how you can also make use of the Web Components base class in OpenUI5/SAPUI5 to also integrate your Web Components and get inspired by the solution to generate a custom UI5 library providing the Web Components control wrappers for the native ones.
The Key to Digital Success_ A Comprehensive Guide to Continuous Testing Integ...kalichargn70th171
In today's business landscape, digital integration is ubiquitous, demanding swift innovation as a necessity rather than a luxury. In a fiercely competitive market with heightened customer expectations, the timely launch of flawless digital products is crucial for both acquisition and retention—any delay risks ceding market share to competitors.
Unveiling the Advantages of Agile Software Development.pdfbrainerhub1
Learn about Agile Software Development's advantages. Simplify your workflow to spur quicker innovation. Jump right in! We have also discussed the advantages.
Project Management: The Role of Project Dashboards.pdfKarya Keeper
Project management is a crucial aspect of any organization, ensuring that projects are completed efficiently and effectively. One of the key tools used in project management is the project dashboard, which provides a comprehensive view of project progress and performance. In this article, we will explore the role of project dashboards in project management, highlighting their key features and benefits.
14 th Edition of International conference on computer visionShulagnaSarkar2
About the event
14th Edition of International conference on computer vision
Computer conferences organized by ScienceFather group. ScienceFather takes the privilege to invite speakers participants students delegates and exhibitors from across the globe to its International Conference on computer conferences to be held in the Various Beautiful cites of the world. computer conferences are a discussion of common Inventions-related issues and additionally trade information share proof thoughts and insight into advanced developments in the science inventions service system. New technology may create many materials and devices with a vast range of applications such as in Science medicine electronics biomaterials energy production and consumer products.
Nomination are Open!! Don't Miss it
Visit: computer.scifat.com
Award Nomination: https://x-i.me/ishnom
Conference Submission: https://x-i.me/anicon
For Enquiry: Computer@scifat.com
UI5con 2024 - Boost Your Development Experience with UI5 Tooling ExtensionsPeter Muessig
The UI5 tooling is the development and build tooling of UI5. It is built in a modular and extensible way so that it can be easily extended by your needs. This session will showcase various tooling extensions which can boost your development experience by far so that you can really work offline, transpile your code in your project to use even newer versions of EcmaScript (than 2022 which is supported right now by the UI5 tooling), consume any npm package of your choice in your project, using different kind of proxies, and even stitching UI5 projects during development together to mimic your target environment.
Artificia Intellicence and XPath Extension FunctionsOctavian Nadolu
The purpose of this presentation is to provide an overview of how you can use AI from XSLT, XQuery, Schematron, or XML Refactoring operations, the potential benefits of using AI, and some of the challenges we face.
Consistent toolbox talks are critical for maintaining workplace safety, as they provide regular opportunities to address specific hazards and reinforce safe practices.
These brief, focused sessions ensure that safety is a continual conversation rather than a one-time event, which helps keep safety protocols fresh in employees' minds. Studies have shown that shorter, more frequent training sessions are more effective for retention and behavior change compared to longer, infrequent sessions.
Engaging workers regularly, toolbox talks promote a culture of safety, empower employees to voice concerns, and ultimately reduce the likelihood of accidents and injuries on site.
The traditional method of conducting safety talks with paper documents and lengthy meetings is not only time-consuming but also less effective. Manual tracking of attendance and compliance is prone to errors and inconsistencies, leading to gaps in safety communication and potential non-compliance with OSHA regulations. Switching to a digital solution like Safelyio offers significant advantages.
Safelyio automates the delivery and documentation of safety talks, ensuring consistency and accessibility. The microlearning approach breaks down complex safety protocols into manageable, bite-sized pieces, making it easier for employees to absorb and retain information.
This method minimizes disruptions to work schedules, eliminates the hassle of paperwork, and ensures that all safety communications are tracked and recorded accurately. Ultimately, using a digital platform like Safelyio enhances engagement, compliance, and overall safety performance on site. https://safelyio.com/
Energy consumption of Database Management - Florina Jonuzi
Jist of Java
1. JAVA QUICKY
Data Structures Algorithms Concepts
Linked Lists Breadth First Search Bit Manipulation
Binary Trees Depth First Search Singleton Design Pattern
Tries Binary Search Factory Design Pattern
Stacks, Queues Merge Sort Memory (Stack vs Heap)
HEAPS (min, max) Quick Sort Recursion
Vectors / ArrayLists Tree Insert / Find … Big-O Time
Hash Tables
JAVA CORE CONCEPTS
1. Java concurrency in practice: http://jcip.net/
2. CONCURRENT CLASSES: CopyOnWriteArrayList, ConcurrentHashMap, CopyOnWriteArraySet
3. Covariant Return Type
Covariant return type return type may vary in direction of subclass.
Starting Java5 possible to override method by return type if subclass overrides any method whose return type is
Non-Primitive but it changes its return type to subclass type. Let's take a simple example:
class A {
A get() {return this;}
}
class B extends A {
B get() {return this;} // overloads – not overrides A::get ()
void message() {System.out.println("Welcome to covariant return type");}
public static void main(String args[]) {
new B().get().message();
}
}
Output: Welcome to covariant return type
4. Abstract Class
Abstract class = abstract concept = template. Can’t be instantiated. The subclasses implement methods.
May contain static data. Abstract methods automatically abstract class and must be declared as such.
A class may be declared abstract even if it has no abstract methods Prevents intances.
5. Interface vs Abstract class
Abstract class can have instance methods with default behavior. Interface only declares constants and instance
methods, no default behavior. An interface has all public members and no implementation. An abstract class is a
class which may have the usual flavors of class members (private, protected, etc.), but has some abstract
methods.
Feature Interface Abstract class
Multiple inheritance YES NO
Default implementation NO. Just signatures YES - complete or default impl that's
overloadable.
Access Modifiers NO YES
2. 6. public, private, protected, default …
* public: Visible everywhere (across packages). Field visible only if class public
* private: Visible only to method of the class
* protected: Visible in package + subclasses – even subclasses in different package.
* default: What you get by. Visible within package.
7. static
Per class, not per object. Static members usable without instance.
Static methods = final, because overriding done based on the type of the object, and static metho ds are attached
to a class, not an object.
A static method in a super-class can be shadowed by another static method in a subclass, as long as the original
method was not declared final. However, you can't override a static method with a nonstatic method. Can't
change a static method into an instance method in a subclass.
8. Checked / UnChecked Exception
Checked = subclass or = Exception; not RuntimeException. Checked exception are those which the Java
compiler forces you to catch. e.g. IOException thrown by java.io.FileInputStream's read() method is a checked
Exceptions.
Unchecked exceptions are RuntimeException, Error, or their subclasses. With an unchecked exception,
compiler doesn't force client programmers to catch the exception or declare it in a throws clause. Client
programmers don’t know that the exception could be thrown. eg, StringIndexOutOfBoundsException thrown by
String's charAt() method.
9. What's New in Java 1.5? (ie Java 5) http://www.cs.indiana.edu/classes/jett/sstamm/
1. Generics
2. For/in loop
3. Autoboxing/Unboxing
4. Typesafe Enums
5. Varargs
6. Static Import
7. Annotations (Metadata)
10.Serialization
Mechanism to save state of object by converting it to a byte stream
11.Serialize an object to a file
Implement interface Serializable. Pass instance to ObjectOutputStream which is connected to FileOutputStream.
12.Which methods of Serializable interface should I implement?
Has none.
13.Customize seralization
Implement Externalizable::readExternal and Externalizable::writeExternal.
14.When you serialize, what happens to object references within object?
The serialization mechanism generates an object graph for serialization. Thus it determines whether the included
object references are serializable or not. This is a recursive process. Thus when an object is serialized, all the
included objects are also serialized alongwith the original obect.
15.Serialization: Note this
All included (contained?) objects are also Serializable. If any of the objects is not serializable then it throws a
NotSerializableException.
16.Static fields during serialization
There are three exceptions in which serialization doesnot necessarily read and write to the stream. These are
1. Serialization ignores static fields, because they are not part of any particular state
2. Base class fields are only handled if the base class itself is Serializable.
3. Transient fields.
17.If I want an object of my class to be thrown as an exception object, what should I do?
Extend from Exception or a subclass of it.
18.If you already inherit, can’t inherit also from “Exception” class!
19.Difference between 2 approaches to exception handling
1> try catch block and
2> specifying the candidate exceptions in the throws clause?
20.Is it necessary that each try block must be followed by a catch block?
No – either “catch” or “finally” block.
3. 21.If I write return at the end of the try block, will the finally block still execute?
Yes.
22.If I write System.exit (0); at the end of the try block, will the finally block still execute?
No in this case the finally block will not execute because when you say System.exit (0); the control immediately
goes out of the program, and thus finally never executes.
23.final, finally, and finalize
• final – declares a constant (like “const” in C++) or method can't be overridden.
• finally – finally block always executes when try block exits – even if unexpected exception occurs. Allows
localizing cleanup code accidentally bypassed by return / continue / break.
• finalize() – method helps garbage collector. Invoked before object is discarded by garbage collector, allowing
it to clean up its state.
24.Difference among String, StringBuffer, and StringBuilder?
String = immutable; StringBuffer = mutable.
o int x=10; String s1 = “” + x;
o String s2 = Integer.toString(x);
o String s3 = String.valueOf(x);
StringBuffer: thread-safe, has append(), insert().. Used when mutable char-strings needed.
Disadvantage is, all public methods are synchronized => slow.
StringBuilder (JDK5+) is designed for single threaded => no sync => faster.
http://docs.oracle.com/javase/1.5.0/docs/api/java/lang/StringBuffer.html
25.Exceptions – note this
The Java Language Specification describes how try-catch-finally is executed. Having no catch is equivalent to not
having a catch able to catch the given Throwable.
If execution of the try block completes abruptly because of a throw of a value V, then there is a choice:
o If the run-time type of V is assignable to the parameter of any catch clause of the try statement, then
…(whatever)…
But if the run-time type of V is not assignable to the parameter of any catch clause of the try
statement, then the finally block is executed. Then there is a choice:
* If the finally block completes normally, then the try statement completes abruptly because of a throw of
the value V.
* If the finally block completes abruptly for reason S, then the try statement completes abruptly for reason S
(and the throw of value V is discarded and forgotten).
26.Java: http://www.oracle.com/technetwork/topics/newtojava/overview/index.html
27.New loop syntax: for (T e : anArray)
28.Implementing hashCode
If a class overrides equals, it must override hashCode. When both overridden, equals and hashCode must use
the same set of fields. If two objects are equal, then their hashCode values must be equal as well. If object is
immutable, hashCode can be “cached” and “lazy initialized”
[http://www.javapractices.com/topic/TopicAction.do;jsessionid=FC37D716710D81A1F389AE39715B672C?Id=28].
29.Class loader searches $CLASSPATH for A.class, JIT compiling of .class byte-code files
30.javadoc processes comments of type /** ... */
31.Java: no stack objects, all on heap
32.Types (study more)
int, Integer
float, Float
Byte, Double
String - fixed length strings
StringBuffer - variable length strings
StringBuilder
int i = 4;
String s = String.valueOf(i); => s is "4"
int a = Integer.parseInt("4"); => a is 4
"blah" + "blah" => "blahblah"
BigDecimal - string rep for floats for DB storing
<anyObj>.toString()
Arrays cant specify size: Typename[] varname; => array. (Cant say Typename[3] varname)
Also, it just creates array object not elements; Typename[] varname; varname[i] = new Typename;
4. Out of bounds access: ArrayIndexOutOfBoundsException, Uninit access: NullPointerException
static final int version = 1; // same as "const int version=1;" in C++
33.Assignments make 2 variables refer to same object unlike in C++
34.To copy objects, define and use clone():
class Data implements Cloneable {
public int data = 0;
public Data(int d) { data = d; }
public Object clone() {
Data d = (Data) super.clone();
d.data = data;
return d;
}
}
...
Data a = new Data(1); // a.data is 1
Data b = new Data(2); // b.data is 2
b = a.clone(); // b.data and a.data are 1
a.data = 3; // b.data is 1, a.data is 3
35.JVM continues to execute threads until either of the following occurs:
1. exit method of class "Runtime" gets called and security manager has permitted exit operation.
2. All threads that are not daemon threads died, either by returning from call to run() or by throwing an exception
that propagates beyond run().
36.Two Java primitive types are equal (using the == operator) when they have the same value (e.g., "3 == 3").
However, two object variables are equal if and only if they refer to the same instantiated object--a "shallow"
comparison.
37.To perform a "deep" comparison, the convention is to define a method called equals(). You would rewrite Data
as:
class Data {
public int data = 0;
public Data(int d) { data = d; }
boolean equals(Data d) {
return data == d.data;
}
}
...
Data a = new Data(1);
Data b = new Data(1);
// a.equals(b) is true!!!!
38.Interfaces
o Interface defines protocol of communication between objects. Group of related methods with empty bodies.
o An interface definition contains method declarations or constant definitions.
o Class implementing interface _must_ implement _all_ methods of it.
o Interface can be used anywhere a type can be.
o public interface OperateCar extends Interface1, Interface2 {
int numWheels = 4;
void TurnRight(int startingSpeed, int endingSpeed, int radius);
…
}
o An interface can extend multiple interfaces (multiple “inheritance” not supported in Java).
o All methods in an interface are inherently public => Specifier omitted.
o Interface obviously can’t contain implementation bodies.
o All variables must be initialized and are all public static final.
5. 39.Primitive data-types as objects and seamless conversions: java.lang.Number:
o Byte, Character, Short, Integer, Long, Float, Double, BigInteger, BigDecimal, AtomicInteger, AtomicLong
40.Java Generics: http://docs.oracle.com/javase/tutorial/java/generics/index.html
o There aren't multiple copies of the code--not in source, not in binary, not on disk and not in memory. Single copy
of a Java Generic.
o Even return types can be templatized: boolean same = Util.<Integer, String>compare(p1, p2);
o Bounded type parameters: public <U extends Number> void inspect(U u){ … }
o Multiple bounds: class D <T extends A & B & C> { … }
Each bound is imposed
If a bound is a class and other bounds interfaces, the class name must be first in list.
o http://docs.oracle.com/javase/tutorial/java/generics/boundedTypeParams.html
o Integer and Double are subclasses of Number. But, Box<Integer> and Box<Double> are not subtypes of
Box<Number>.
o In generic code, the question mark (?), called the wildcard, represents an unknown type.
List<? extends String> list2 = new ArrayList<>();
o Bounded wildcards: To write the method that works on lists of Number and the subtypes of Number, such
as Integer, Double, and Float, you would specify List<? extends Number>. The term List<Number> is more
restrictive than List<? extends Number> because the former matches a list of type Number only, whereas the
latter matches a list of type Number or any of its subclasses.
o Unbounded wildcards: Consider the following method, printList:
public static void printList(List<Object> list) {
for (Object elem : list)
System.out.println(elem + " ");
System.out.println();
}
The goal of printList is to print a list of any type, but it fails to achieve that goal — it prints only a list of
Object instances; it cannot print List<Integer>, List<String>, List<Double>, and so on, because they
are not subtypes of List<Object>. To write a generic printList method, use List<?>:
public static void printList(List<?> list) {
for (Object elem: list)
System.out.print(elem + " ");
System.out.println();
}
o A lower bounded wildcard restricts unknown type to be a specific type or a super type of that type: List<?
super Integer> list;
o During the type erasure process, the Java compiler erases all type parameters and replaces each with its first
bound if the type parameter is bounded, or Object if the type parameter is unbounded.
o Type Erasure: Java compiler replaces unbounded type parameters with Object and bounded type parameters
with first bound: http://docs.oracle.com/javase/tutorial/java/generics/genTypes.html
o Compiler generated Bridge method to preserve polymorphism when type erasure causes compiler-unanticipated
problems.
6. o A reifiable type is a type whose type information is fully available at runtime. This includes primitives, non-
generic types, raw types, and invocations of unbound wildcards. Examples of non-reifiable types are
List<String> and List<Number>; the JVM cannot tell the difference between these types at runtime. They
cannot be used in an instanceof expression, for example, or as an element in an array.
41.Packages: To create a package put a package statement with its name at of every source file that contains the
types (classes, interfaces, enumerations, and annotation types) that you want to include in the package.
The package statement must be the first line in the source file. There can be only one package statement in each
source file, and it applies to all types in the file.
42.Once members of a package imported as “static”, they can be used without package name qualification:
import static java.lang.Math.*; // Use sparingly to maintain readability
double r = cos(PI * theta);
Otherwise:
import static java.lang.Math.PI;
double r = Math.cos(Math.PI * theta);
43.public abstract class Graphic { ... }
44.Lambda expressions: A lambda expression consists of:
o (a,b, c): comma-separated list of formal parameters enclosed in parentheses (You may omit the data type of the
parameters in a lambda expression. In addition, you may omit the parentheses if there is only one parameter)
o ->: the arrow
o statement(s): a body consisting of single expression or a statement block. If single expression, Java returns its
value => don’t need “return” statement.
o {} – but no need of {} for void method.
o Examples:
email -> System.out.println(email)
IntegerMath addition = (a, b) -> a + b;
IntegerMath subtraction = (a, b) -> a - b;
45.Difference between equals() method and == ?
== compares references. object.equals() compares values.
46.Steps in JDBC connection
While making a JDBC connection we go through the following steps :
Step 1 : Register the database driver by using :
Class.forName(" driver classs for that specific database" );
Step 2 : Now create a database connection using :
Connection con = DriverManager.getConnection(url,username,password);
Step 3: Now Create a query using :
Statement stmt = Connection.Statement("select * from TABLE NAME");
Step 4 : Exceute the query :
stmt.exceuteUpdate();
47.Applet:
* Inherit from Applet class (no file IO, sockets, menu, lifecycle events)
* init() = ctor, start(), stop(), destroy()...dispose()...super.dispose()
* (1) extend JApplet, implement init(), start(), stop(), destroy().
o To deploy, make a JAR package and sign it.
o Launch using (1) JNLP or (2) specify applet launch properties in applet tag.
48.HTML embed applet like img: <applet code=AppletName.class width=w height=h> [<param K-V
params>]</applet>
49.Nested Class:
o Static Nested Classes: Can’t access other members of enclosing class
o Inner Classes: Can access other members of enclosing class even if private
o OuterClass.InnerClass innerObject = outerObject.new InnerClass();
o Shadowing: Inner class member with same name shadows outer class’s member.
7. Refer to OuterClass.this.member
o Anonymous class: HelloWorld spanishGreeting = new HelloWorld() {
public void greet() {}
public static void main(String[] args) {}
}
50.Java Classloader is part of JRE that dynamically loads Java classes into JVM on demand. The Java run time
system does not need to know about files and file systems because of classloaders. Each Java class must be
loaded by a class loader. When JVM is started, three class loaders are used:
1. Bootstrap class loader: loads core Java libraries located in <JAVA_HOME>/jre/lib dir
2. Extensions class loader:
loads code in extensions dirs (<JAVA_HOME>/jre/lib/ext) or dir specified by java.ext.dirs system
property
Implemented by sun.misc.Launcher$ExtClassLoader class
3. System class loader:
loads code found on java.class.path ($CLASSPATH env var)
implemented by the sun.misc.Launcher$AppClassLoader class
JAVA MEMORY MANAGEMENT
51.Garbage collection
Identifies and discards objects no longer needed for resource reuse.
GC Roots = local vars, the Main thread, Static vars of main class
52.Finalization
The purpose of finalization is to give an unreachable object the opportunity to perform any cleanup processing
before the object is garbage collected.
53.Can an unreachable object become reachable again?
An unreachable object may become reachable again. This can happen when the object's finalize() method is
invoked and the object performs an operation which causes it to become accessible to reachable objects.
54.Garbage collector is a daemon thread that runs periodically to reclaim sets of objects. Uses a tree topology to find
recoverable objects. http://www.oracle.com/technetwork/java/gc-tuning-5-138395.html
55.http://www.infoq.com/articles/Java_Garbage_Collection_Distilled,
http://javarevisited.blogspot.com/2011/04/garbage-collection-in-java.html
56.REFERENCES – subclasses of java.lang.ref.Reference<T>
1) StrongReference – Regular reference: Foo f = new Foo();
2) WeakReference – Isn't strong enough to force referent to stay in memory => en-queued/cleared ASAP
class MyEntry<K,V> extends WeakReference<Object> implements Map.Entry<K,V>
MyEntry<String,String> table = new MyEntry<>();
table = null; // And its probly gone…! Aggressively…
System.gc(); sleep(5000); // If table not dead yet, now for sure it’d be…
3) SoftReference – Like WeakReference but less aggressive => en-queued/cleared as late as possible – ie
either in next cycle of garbage collection or when VM is about to go out of memory => guaranteed cleared
before VM throws OutOfMemoryError…
8. Object obj = new Object();
SoftReference softRef = new SoftReference(obj /*, ReferenceQueue rq = new ReferenceQueue() */);
obj = null;
Object obj2(softRef.get());
if (obj2 == null) {
// => Garbage collector freed softRef referent!
}
4) PhantomReference – Can’t retrieve referent (get() returns null). Useful only as a signal to know when
referent is already finalized and en-queued in ReferenceQueue (after death!). Use when finalize() method is
not sensible.
public class ConnectionPhantomReference extends PhantomReference {
private DB db;
public ConnectionPhantomReference (Conn c) { db.open(c); … }
public void cleanup() { db.close(); }
}
// Create a daemon thread (Thread.setDaemon(true)) to handle ReferenceQueue<>
5) ReferenceQueue – Supply-able as second arg to ref-ctors. After referent collected, referent value itself en-
queued to supplied ReferenceQueue. This allows performing clean up operations on referent obj.
6) References on reference: https://weblogs.java.net/blog/2006/05/04/understanding-weak-references,
http://docs.oracle.com/javase/6/docs/api/java/lang/ref/Reference.html,
http://docs.oracle.com/javase/6/docs/api/java/lang/ref/ReferenceQueue.html,
http://neverfear.org/blog/view/150/Strong_Soft_Weak_and_Phantom_References_Java
57.-XX:GCTimeRatio=99 implies 1% GC time
58.–Xmx<n> is tuning parameter to set Max available heap size for an app; -Xms<n> sets initial heap size
59.Native_Memory = Process_Size – Max_Heap_Size – Max_Perm_Size
60.JAVA HEAP TERMINOLOGY: YOUNG, OLD, PERMANENT GENERATIONS
HotSpot JVM uses following memory-pools for serial garbage collection:
1. http://www.maths.lse.ac.uk/Courses/MA407/gcsurvey.pdf,
http://middlewaremagic.com/weblogic/?tag=young-generation,
http://openjdk.java.net/groups/hotspot/docs/StorageManagement.html,
http://java.sun.com/j2se/reference/whitepapers/memorymanagement_whitepaper.pdf,
http://developers.sun.com/learning/javaoneonline/2006/coreplatform/TS-1168.pdf,
https://blogs.oracle.com/jonthecollector/entry/presenting_the_permanent_generation
2. Young Generation / Eden Space (heap): Pool objects initially allocated into
3. Old Generation / Survivor Space (heap): Objects that survived garbage collection of Eden space
4. Tenured Generation (heap): Pool of objects existed for some time in Survivor space.
5. Permanent Generation (non-heap): Pool of reflective data of VM itself (class, method objects). With
VMs using class data sharing, this generation is divided into read-only and read-write areas.
6. Code Cache (non-heap): memory for compilation and storage of native code (HotSpot JVM)
9. 7. JVM has three generations: young, old and permanent.
Young => most objects
Old => large objects / objects that survived few collections
Permanent => objects convenient to manage (objects describing classes, methods).
61.JAVA MEMORY LEAKS
Scenario: A long-life class “contains” short-lived large objects (say a map of stuff), map contents may
not be released until the long-life (singleton?) object isn’t released, causing leak = size of map
Signs: OutOfMemoryError or slowness (frequent gc)
Detection:
o Invoke JVM with –verbose:gc or –Xloggc: turns on GC logging
o Use free tool: JTune – graphs memory usage over time
o Use paid tool: HeapAudit to understand JVM mem allocations
o Eclipse has profiling filters (Memory Analysis, Exec Time Analysis etc) in Profiling Monitor – nice GUI
o Once convinced memory leak, built-in “hprof” tool – invoke JVM with –Xrunhprof:heap=sites shows
lines of code and allocations. Prints usage breakdown after your kill -3 the program.
Solution:
o Use WeakReference – For the map in context, use Entry<K,V> object that extends WeakReference<T>
class and overload get().
class WeakHashMap<K,V> implements Map<K,V> {
private static class Entry<K,V> extends WeakReference<K> implements Map.Entry<K,V> {
private V value; private Entry<K,V> next; …
}
// get below returns a strong reference so you’re not losing value
public V get (Object key) { … go thru Entry-s … return e.value; else return null; }
}
o Also make sure to use ReferenceQueue (WeakReference has ctor that accepts q), GC submits handles
of garbage collected objects back in this q.
JAVA MULTI-THREADING
62.Thread creation
(1) Implement Runnable interface or (2) Inherit from Thread class. Implementing Runnable better if you
anticipate multiple inheritance.
63.Java Thread Safety – Methods/Choices
Different ways to make program thread safe:
1. Synchronization is the easiest and most widely used tool for thread safety in java.
2. Use of Atomic Wrapper classes from java.util.concurrent.atomic package. For example AtomicInteger
3. Use of locks from java.util.concurrent.locks package.
4. Using thread safe collections, check this post for usage of ConcurrentHashMap for thread safety.
5. Using volatile keyword with variables to make every thread read the data from memory, not read from thread
cache.
64.Java Thread Pool = ExecutorService. See here: here and here!
65.Concurrent Collections: BlockingQueue, ConcurrentMap, ConcurrentHashMap,
ConcurrentNavigableMap, ConcurrentSkipListMap
66.Thread Pools: newFixedThreadPool, newCachedThreadPool, newSingleThreadExecutor,
ScheduledThreadPoolExecutor
10. 67.AtomicInteger has synchronized incrementAndGet, decrementAndGet methods.
68.notify() v/s notifyAll() (Doug Lea in his famous book): If a notify() and Thread.interrupt() happen at the same
time, the notify might actually get lost => dramatic implications. notifyAll() is a safer choice even though you pay
the price of overhead (waking too many threads most of the time).
69.Volatile variable: Single copy of member across threads: If multiple threads update a “volatile” member at the
same time, updates to volatile member reflect immediately to other threads. That is, each thread may make its
own cache of Object’s members other than volatile members.
JAVA COLLECTIONS
70.HashMap / Map
Map: key-value; no duplicate keys
SortedMap: keys ordered
Map = Interface, HashMap implements it
Multimap: No such thing in Java
71.HashMap / HashTable
1) HashMap – NULLs
2) HashMap – order not guaranteed
3) HashMap – not synchronized; Hashtable is synchronized.
72.Map v/s Hashtable
1. Map = interface, Hashtable = concrete impl.
2. Map allows you to iterate over keys, values, or key-value pairs; Hashtable does not provide the third option.
3. Map = safely remove entries in the midst of iteration; Hashtable = not.
4. Finally, Map fixes a minor deficiency in the Hashtable interface. Hashtable has a method called contains, which
returns true if the Hashtable contains a given value. Given its name, you'd expect this method to return true
if the Hashtable contained a given key, because the key is the primary access mechanism for a Hashtable. The
Map interface eliminates this source of confusion by renaming the method containsValue. Also, this
improves the interface's consistency — containsValue parallels containsKey.
73.Hashtable v/s Collections.synchronizedMap v/s ConcurrentHashMap
1. Hashtable synchronized, old (extends obsolete Dictionary), adapted to fit Map interface; doesn’t scale well.
2. ConcurrentHashMap – concurrent unblocked modifications by several threads; parallel reads; only when entry
not found it (locks? and) rechecks; Bucket locks (2^16) for write and deletion; as performant as HashMap
3. Collections.synchronizedMap – blocking map => consistent but slow, just like Hashtable.
4. http://jcip.net/ (Java concurrency in practice)
5.
Property HashMap Hashtable ConcurrentHashMap
Null values/keys Fine No No
Thread-safe (Synchronized?) No Yes Yes
Lock mechanism NA Whole Map
locked
Portions locked
Iterator Fail-Fast Fail-Safe No
74.BlockingQueue
– is an interface
– Exactly a Producer-Consumer Bounded buffer implementation
– Null elements not allowed, throws NPE
– All implement blocking put() and take() methods
– add() throws exception if it can’t add, offer() returns bool and is preferred!
Following all implement BlockingQueue interface:
o ArrayBlockingQueue – size bound
11. o DelayQueue – object should ripen (delay) before take()
o LinkedBlockingDeque – elastic size / size optional double ended
o LinkedBlockingQueue – elastic size / size optional
o PriorityBlockingQueue – priority attribute (heap?)
o SynchronousQueue – producer/writer blocked until consumer/reader calls take()
o LinkedTransferQueue –
http://docs.oracle.com/javase/7/docs/api/java/util/concurrent/BlockingQueue.html
public class BlockingQueueExample {
public static void main(String[] args)
throws Exception {
BlockingQueue queue = new
ArrayBlockingQueue(1024);
Producer producer = new
Producer(queue);
Consumer consumer = new
Consumer(queue);
new Thread(producer).start();
new Thread(consumer).start();
Thread.sleep(4000);
}
}
ArrayBlockingQueue<>
http://tutorials.jenkov.com/java-util-
concurrent/blockingqueue.html
public class Producer implements
Runnable{
protected BlockingQueue queue = null;
public Producer(BlockingQueue queue) {
this.queue = queue;
}
public void run() {
try {
queue.put("1");
Thread.sleep(1000);
queue.put("2");
Thread.sleep(1000);
queue.put("3");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public class Consumer implements
Runnable{
protected BlockingQueue queue = null;
public Consumer(BlockingQueue queue) {
this.queue = queue;
}
public void run() {
try {
System.out.println(queue.take());
System.out.println(queue.take());
System.out.println(queue.take());
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
PRODUCER CONSUMER BOUNDED-BUFFER IMPL IN JAVA
75.Vector / ArrayList
Vector synchronized.. so.. ArrayList faster. Use CopyOnWriteArrayList<> if modifications expected during iter
76.Swing / Awt
AWT = heavy-weight components. Swings = light-weight components. Swing => faster.
12. 77.Iterator
= java.util.Iterator interface allows traversing collections. Implements Iterator Design Pattern.
78.collections-framework-interfaces
79.CharSequence
80.Concurrent Collections: BlockingQueue, ConcurrentMap, ConcurrentHashMap,
ConcurrentNavigableMap, ConcurrentSkipListMap
81.Collections: http://docs.oracle.com/javase/tutorial/collections/interfaces/collection.html
o Core collections
o Set: No duplicates
SortedSet: naturally ordered ascending
Set.add(e) returns null upon trying to add duplicate e
o List: Ordered sequence; duplicates possible
o Queue: may provide a FIFO interface
PriorityQueue
o Deque: FIFO or LIFO
o Map: key-value; no duplicate keys
o SortedMap: keys ordered
o Multimap: No such thing in Java
o To remove all: c.removeAll(Collections.singleton(e));
o To remove “null”: c.removeAll(Collections.singleton(null));
o To remove dups:
Remove duplicates only:
public static <E> Set<E> removeDups(Collection<E> c) {
return new LinkedHashSet<E>(c);
}
Remove duplicates preserve order:
public static <E> Set<E> removeDups(Collection<E> c) {
return new LinkedHashSet<E>(c);
}
JAVA MISC
82.JAR files, manifest file, creating, modifying them:
http://docs.oracle.com/javase/tutorial/deployment/jar/index.html
83.Reflection API: When programs need to check or modify runtime behavior of applications running in JVM.
o http://docs.oracle.com/javase/tutorial/reflect/index.html
o Class c = Object.getClass()
o Class c = Class.forName("com.duke.MyLocaleServiceProvider");
o Class c = Double.TYPE;
o getSuperClass()
o getClasses()
o getEnclosingClass()
o getDeclaredClasses()
13. o getDeclaredField(),getDeclaredFields(),getDeclaredMethod(),getDeclaredMethods(),
getDeclaredConstructor(),getDeclaredConstructors()
o … Similar Reflection APIs for Members, Arrays and Enumerated types…
84.SDP (Sockets Direct Protocol) http://docs.oracle.com/javase/tutorial/sdp/index.html
o java.net : Socket, ServerSocket
85.http://en.wikipedia.org/wiki/Java_virtual_machine
86.http://en.wikipedia.org/wiki/Comparison_of_Java_virtual_machines
87. Iterators differ from enumerations in two ways
Iterators allow caller to remove elements from collection during iteration; and Method names are improved.
Enumeration Iterator
---------------- ----------------
hasMoreElement() hasNext()
nextElement() next()
N/A remove()
88.Very good Java resource:
http://www.oracle.com/webfolder/technetwork/tutorials/obe/java/gc01/index.html