├── .gitignore
├── Databases
└── Database (Oracle).txt
├── Framework and Libraries
├── Hibernate.txt
├── Java Servlets.txt
├── Java Testing With JUnit.txt
└── Spring.txt
├── Images
├── Java Collections Hierarchy.jpg
└── Java Collections.jpg
├── Java Core
├── JVM Internals.txt
├── Java Applets.txt
├── Java Assertions.txt
├── Java Basics.md
├── Java Collections.txt
├── Java Concurrency.txt
├── Java Exceptions.txt
├── Java GUI.txt
├── Java Generics.txt
├── Java IO.txt
├── Java Interfaces.txt
├── Java JDBC.txt
└── Java Version Specific.txt
├── README.md
└── Software Design
├── Design Patterns.txt
├── OOP.txt
└── Software Design.txt
/.gitignore:
--------------------------------------------------------------------------------
1 | ### JetBrains template
2 | # Covers JetBrains IDEs: IntelliJ, RubyMine, PhpStorm, AppCode, PyCharm, CLion
3 |
4 | *.iml
5 |
6 | ## Directory-based project format:
7 | .idea/
8 |
9 | ## File-based project format:
10 | *.ipr
11 | *.iws
12 |
13 | ## Plugin-specific files:
14 |
15 | # IntelliJ
16 | /out/
17 |
18 | # mpeltonen/sbt-idea plugin
19 | .idea_modules/
20 |
21 | # JIRA plugin
22 | atlassian-ide-plugin.xml
23 |
24 | # Crashlytics plugin (for Android Studio and IntelliJ)
25 | com_crashlytics_export_strings.xml
26 | crashlytics.properties
27 | crashlytics-build.properties
28 |
29 |
30 | ### Eclipse template
31 | *.pydevproject
32 | .metadata
33 | .gradle
34 | bin/
35 | tmp/
36 | *.tmp
37 | *.bak
38 | *.swp
39 | *~.nib
40 | local.properties
41 | .settings/
42 | .loadpath
43 |
44 | # Eclipse Core
45 | .project
46 |
47 | # External tool builders
48 | .externalToolBuilders/
49 |
50 | # Locally stored "Eclipse launch configurations"
51 | *.launch
52 |
53 | # CDT-specific
54 | .cproject
55 |
56 | # JDT-specific (Eclipse Java Development Tools)
57 | .classpath
58 |
59 | # Java annotation processor (APT)
60 | .factorypath
61 |
62 | # PDT-specific
63 | .buildpath
64 |
65 | # sbteclipse plugin
66 | .target
67 |
68 | # TeXlipse plugin
69 | .texlipse
70 |
71 | ### SublimeText template
72 | # cache files for sublime text
73 | *.tmlanguage.cache
74 | *.tmPreferences.cache
75 | *.stTheme.cache
76 |
77 | # workspace files are user-specific
78 | *.sublime-workspace
79 |
80 | # project files should be checked into the repository, unless a significant
81 | # proportion of contributors will probably not be using SublimeText
82 | # *.sublime-project
83 |
84 | # sftp configuration file
85 | sftp-config.json
86 |
87 |
88 |
--------------------------------------------------------------------------------
/Databases/Database (Oracle).txt:
--------------------------------------------------------------------------------
1 | ------------------ SQL (Oracle applied)
2 | What are DML and DDL
3 | DDL
4 | Data definition language (DDL) statements define, structurally change, and
5 | drop schema objects.
6 | An implicit COMMIT occurs immediately before the database executes a DDL
7 | statement and a COMMIT or ROLLBACK occurs immediately afterward.
8 | DML
9 | Data manipulation language (DML) statements query or manipulate data in
10 | existing schema objects. Whereas DDL statements enable you to change the
11 | structure of the database, DML statements enable you to query or change the
12 | contents. For example, ALTER TABLE changes the structure of a table, whereas
13 | INSERT adds one or more rows to the table.
14 |
15 | Agregate functions with examples
16 | todo
17 |
18 | What is a nested subquery?
19 | A subquery is a SELECT statement nested within another SQL statement. Subqueries
20 | are useful when you must execute multiple queries to solve a single problem.
21 | These subqueries can reside in the WHERE clause, the FROM clause, or the SELECT clause.
22 | Example:
23 | SELECT first_name, last_name
24 | FROM employees
25 | WHERE department_id
26 | IN (SELECT department_id FROM departments WHERE location_id = 1800);
27 |
28 | Types of indices in Oracle
29 | Oracle Database provides several indexing schemes, which provide complementary
30 | performance functionality. The indexes can be categorized as follows:
31 | B-tree indexes
32 | These indexes are the standard index type. They are excellent for primary
33 | key and highly-selective indexes. Used as concatenated indexes, B-tree
34 | indexes can retrieve data sorted by the indexed columns.
35 | B-tree indexes have the following subtypes:
36 | � Index-organized tables
37 | An index-organized table differs from a heap-organized because the data is
38 | itself the index. See "Overview of Index-Organized Tables" on page 3-20.
39 | � Reverse key indexes
40 | In this type of index, the bytes of the index key are reversed, for
41 | example, 103 is stored as 301. The reversal of bytes spreads out inserts
42 | into the index over many blocks.
43 | � Descending indexes
44 | This type of index stores data on a particular column or columns in
45 | descending order.
46 | � B-tree cluster indexes
47 | This type of index is used to index a table cluster key. Instead of
48 | pointing to a row, the key points to the block that contains rows related
49 | to the cluster key.
50 | Bitmap and bitmap join indexes
51 | In a bitmap index, an index entry uses a bitmap to point to multiple rows.
52 | In contrast, a B-tree index entry points to a single row. A bitmap join
53 | index is a bitmap index for the join of two or more tables.
54 | Function-based indexes
55 | This type of index includes columns that are either transformed by a
56 | function, such as the UPPER function, or included in an expression.
57 | B-tree or bitmap indexes can be function-based.
58 | Application domain indexes
59 | This type of index is created by a user for data in an application-specific
60 | domain. The physical index need not use a traditional index structure and
61 | can be stored either in the Oracle database as tables or externally as a
62 | file.
63 |
64 | What is a hierarchical query? How to create it?
65 | http://docs.oracle.com/cd/B19306_01/server.102/b14200/queries003.htm
66 | If a table contains hierarchical data, then you can select rows in a hierarchical order using the hierarchical query clause:
67 | [ START WITH condition ] CONNECT BY [ NOCYCLE ] condition
68 | Example:
69 | 1)show EXPLAIN PLAN
70 | -- EXPLAIN PLAN
71 | delete PLAN_TABLE where statement_id = 'ago01';
72 | EXPLAIN PLAN SET STATEMENT_ID = 'ago01' FOR
73 | ---------------------- put query below
74 | select /*+ FIRST_ROWS(25) */
75 | decode(message_type, '1','personal', '2','broadcast') as mess_type,
76 | eb_messages_data.*
77 | from eb_messages_data
78 | where message_id in (select message_id
79 | from eb_disposer_mailboxes
80 | where disposer_number like '%3140007')
81 | and message_type = '2';
82 | ----------------------- put query above
83 |
84 | select * from PLAN_TABLE where STATEMENT_ID = 'ago01';
85 |
86 | SELECT lpad('.',level-1, '.')||operation||' '|| options||' '||object_type||' '||object_name "Plan",
87 | cost, bytes, cardinality, access_predicates || filter_predicates as predicates
88 | FROM PLAN_TABLE
89 | CONNECT BY prior id = parent_id
90 | AND prior statement_id = statement_id
91 | START WITH id = 0
92 | AND statement_id = 'ago01'
93 | ORDER BY id;
94 | 2)CONNECT BY Example
95 | SELECT employee_id, last_name, manager_id
96 | FROM employees
97 | CONNECT BY PRIOR employee_id = manager_id;
98 | 3)level example
99 | SELECT employee_id, last_name, manager_id, LEVEL
100 | FROM employees
101 | CONNECT BY PRIOR employee_id = manager_id;
102 | 4)START WITH Examples
103 | SELECT last_name, employee_id, manager_id, LEVEL
104 | FROM employees
105 | START WITH employee_id = 100
106 | CONNECT BY PRIOR employee_id = manager_id
107 | ORDER SIBLINGS BY last_name;
108 |
109 | What is query tuning? How to tune a query?
110 | http://www.dba-oracle.com/art_sql_tune.htm
111 | http://www.akadia.com/services/ora_query_tuning.html
112 | http://www.orafaq.com/wiki/Oracle_database_Performance_Tuning_FAQ
113 |
114 | Partitioning and methods of partitioning
115 | Partitioning enables you to decompose very large tables and indexes into
116 | smaller and more manageable pieces called partitions. Each partition is an
117 | independent object with its own name and optionally its own storage characteristics.
118 | From the perspective of an application, only one schema object exists. DML statements require no modification
119 | to access partitioned tables. Partitioning is useful for many different types of database applications, particularly
120 | those that manage large volumes of data. Benefits include:
121 | Increased availability
122 | Easier administration of schema objects
123 | Reduced contention for shared resources in OLTP systems
124 | Enhanced query performance in data warehouses
125 | Partitioning Strategies:
126 | Range Partitioning
127 | CREATE TABLE time_range_sales
128 | ( prod_id NUMBER(6)
129 | , cust_id NUMBER
130 | , time_id DATE
131 | , channel_id CHAR(1)
132 | , promo_id NUMBER(6)
133 | , quantity_sold NUMBER(3)
134 | , amount_sold NUMBER(10,2)
135 | )
136 | PARTITION BY RANGE (time_id)
137 | (PARTITION SALES_1998 VALUES LESS THAN (TO_DATE('01-JAN-1999','DD-MON-YYYY')),
138 | PARTITION SALES_1999 VALUES LESS THAN (TO_DATE('01-JAN-2000','DD-MON-YYYY')),
139 | PARTITION SALES_2000 VALUES LESS THAN (TO_DATE('01-JAN-2001','DD-MON-YYYY')),
140 | PARTITION SALES_2001 VALUES LESS THAN (MAXVALUE)
141 | );
142 | List Partitioning
143 | CREATE TABLE list_sales
144 | ( prod_id NUMBER(6)
145 | , cust_id NUMBER
146 | , time_id DATE
147 | , channel_id CHAR(1)
148 | , promo_id NUMBER(6)
149 | , quantity_sold NUMBER(3)
150 | , amount_sold NUMBER(10,2)
151 | )
152 | PARTITION BY LIST (channel_id)
153 | (PARTITION even_channels VALUES (2,4),
154 | PARTITION odd_channels VALUES (3,9)
155 | );
156 | Hash Partitioning
157 | CREATE TABLE hash_sales
158 | ( prod_id NUMBER(6)
159 | , cust_id NUMBER
160 | , time_id DATE
161 | , channel_id CHAR(1)
162 | , promo_id NUMBER(6)
163 | , quantity_sold NUMBER(3)
164 | , amount_sold NUMBER(10,2)
165 | )
166 | PARTITION BY HASH (prod_id)
167 | PARTITIONS 2;
168 |
169 | ------------------ DB
170 | Primary key vs unique key. Differences.
171 |
172 | What types of constraints does one know?
173 | NOT NULL
174 | Allows or disallows inserts or updates of rows
175 | containing a null in a specified column.
176 | Unique key
177 | Prohibits multiple rows from having the same value in
178 | the same column or combination of columns but allows
179 | some values to be null.
180 | Primary key
181 | Combines a NOT NULL constraint and a unique constraint. It prohibits
182 | multiple rows from having the same value in the same column or combination
183 | of columns and prohibits values from being null
184 | Foreign key
185 | Designates a column as the foreign key and establishes a relationship
186 | between the foreign key and a primary or unique key, called the referenced
187 | key.
188 | Check
189 | Requires a database value to obey a specified condition.
190 | REF
191 | Dictates types of data manipulation allowed on values in a REF column and
192 | how these actions affect dependent values. In an object-relational database,
193 | a built-in data type called a REF encapsulates a reference to a row object
194 | of a specified object type. Referential integrity constraints on REF columns
195 | ensure that there is a row object for the REF.
196 |
197 | What is a view/materialized view.
198 | View
199 | A view is a logical representation of one or more tables. In essence,
200 | a view is a stored query. A view derives its data from the tables on which
201 | it is based, called base tables. Base tables can be tables or other views.
202 | All operations performed on a view actually affect the base tables. You can
203 | use views in most places where tables are used.
204 | Materialized View
205 | Materialized views are query results that have been stored or "materialized"
206 | in advance as schema objects. The FROM clause of the query can name tables,
207 | views, and materialized views. Collectively these objects are called master
208 | tables (a replication term) or detail tables (a data warehousing term).
209 |
210 | What kind of joins do you know?
211 | Inner joins
212 | An inner join is a join of two or more tables that returns only rows that
213 | satisfy the join condition. For example, if the join condition is employees.
214 | department_id=departments.department_id, then rows that do not satisfy this
215 | condition are not returned.
216 | Outer joins
217 | An outer join returns all rows that satisfy the join condition and also
218 | returns rows from one table for which no rows from the other table satisfy
219 | the condition. For example, a left outer join of employees and departments
220 | retrieves all rows in the employees table even if there is no match in
221 | departments. A right outer join retrieves all rows in departments even if
222 | there is no match in employees.
223 | Cartesian products
224 | If two tables in a join query have no join condition, then the database
225 | returns their Cartesian product. Each row of one table combines with each
226 | row of the other. For example, if employees has 107 rows and departments
227 | has 27, then the Cartesian product contains 107*27 rows. A Cartesian
228 | product is rarely useful.
229 |
230 | Types of tables (regular, temporary, index-organized etc)
231 | Oracle Database tables fall into the following basic categories:
232 | Relational tables: Relational tables have simple columns and are the most common table type.
233 | A heap-organized table
234 | does not store rows in any particular order. The CREATE
235 | TABLE statement creates a heap-organized table by default.
236 | An index-organized table
237 | orders rows according to the primary key values. For
238 | some applications, index-organized tables enhance performance and use disk
239 | space more efficiently.
240 | An external table
241 | is a read-only table whose metadata is stored in the database but
242 | whose data in stored outside the database.
243 | Object tables: The columns correspond to the top-level attributes of an object type.
244 | --
245 | A table is either permanent or temporary. A permanent table definition and data
246 | persist across sessions. A temporary table definition persists in the same way as a
247 | permanent table definition, but the data exists only for the duration of a transaction or
248 | session. Temporary tables are useful in applications where a result set must be held
249 | temporarily, perhaps because the result is constructed by running multiple operations.
250 |
251 | Are database Indexes useful? What is the role of them?
252 | An index is an optional structure, associated with a table or table cluster,
253 | that can sometimes speed data access. By creating an index on one or more
254 | columns of a table, you gain the ability in some cases to retrieve a small
255 | set of randomly distributed rows from the table. Indexes are one of many means
256 | of reducing disk I/O.
257 | If a heap-organized table has no indexes, then the database must perform a
258 | full table scan to find a value. For example, without an index, a query of
259 | location 2700 in the hr.departments table requires the database to search
260 | every row in every table block for this value. This approach does not scale
261 | well as data volumes increase.
262 |
263 | Why many indexes are not good for performance
264 | Too many indexes will result in more frequent INDEX REBUILD operations which are costly to the database table.
265 | If a table has many indexes and is read heavy and has very less writes (UPDATE / INSERT) instead of SELECT then Indexes will actually speed up the query.
266 | However if there are too many indexes and table has frequent writes then costly Index Rebuild operations will be very frequent.
267 |
268 | What does it mean database de-normalization?
269 | todo
270 |
271 | Which of SELECT, UPDATE, DELETE, ADDs performance is mostly affected by performance of indexes?
272 | todo
273 |
274 | What are ways to increase performance of database
275 | todo
276 |
--------------------------------------------------------------------------------
/Framework and Libraries/Hibernate.txt:
--------------------------------------------------------------------------------
1 | ----------------- Hibernate -----------------
2 |
3 | Benefits and risks of using Hibernate
4 | //todo
5 |
6 | What is a SessionFactory? Is it a thread-safe object?
7 | The main contract here is the creation of Session instances. Usually an
8 | application has a single SessionFactory instance and threads servicing client
9 | requests obtain Session instances from this factory.
10 | The internal state of a SessionFactory is immutable. Once it is created this
11 | internal state is set. This internal state includes all of the metadata about
12 | Object/Relational Mapping.
13 | Implementors must be threadsafe.
14 |
15 | What is the difference between merge and update
16 | saveOrUpdate:
17 | Calls either save or update depending on some checks. E.g. if no identifier
18 | exists, save is called. Otherwise update is called.
19 | save:
20 | Persists an entity. Will assign an identifier if one doesn't exist. If one
21 | does, it's essentially doing an update. Returns the generated ID of the
22 | entity.
23 | update:
24 | Update the persistent instance with the identifier of the given detached
25 | instance. If there is a persistent instance with the same identifier,
26 | an exception is thrown. This operation cascades to associated instances
27 | if the association is mapped with cascade="save-update".
28 | merge:
29 | Copy the state of the given object onto the persistent object with the same
30 | identifier. If there is no persistent instance currently associated with
31 | the session, it will be loaded. Return the persistent instance. If the
32 | given instance is unsaved, save a copy of and return it as a newly
33 | persistent instance. The given instance does not become associated with
34 | the session. This operation cascades to associated instances if the
35 | association is mapped with cascade="merge".
36 | In these cases you need to use merge for updates and persist for saving.
37 | persist:
38 | As mentioned above, this is used on transient objects. It does not return
39 | the generated ID.
40 |
41 | What is Hibernate Query Language (HQL)?
42 | Hibernate uses a powerful query language (HQL) that is similar in appearance
43 | to SQL. Compared with SQL, however, HQL is fully object-oriented and
44 | understands notions like inheritance, polymorphism and association.
45 |
46 | Lazy loading
47 | Proxy pattern.
48 | Say you have a parent and that parent has a collection of children.
49 | Hibernate now can "lazy-load" the children, which means that it does not
50 | actually load all the children when loading the parent. Instead, it loads them
51 | when requested to do so. You can either request this explicitly or, and this
52 | is far more common, hibernate will load them automatically when you try to
53 | access a child.
54 | Lazy-loading can help improve the performance significantly since often you
55 | won't need the children and so they will not be loaded.
56 | Also beware of the n+1-problem. Hibernate will not actually load all
57 | children when you access the collection. Instead, it will load each child
58 | individually. When iterating over the collection, this causes a query for
59 | every child. In order to avoid this, you can trick hibernate into loading
60 | all children simultaneously, e.g. by calling parent.getChildren().size().
61 |
62 | What do you mean by Named � SQL query and how to invoke it?
63 | Named SQL queries may be defined in the mapping document and called in exactly
64 | the same way as a named HQL query. In this case, we do not need to call
65 | addEntity().
66 |
67 |
68 | SELECT person.NAME AS {person.name},
69 | person.AGE AS {person.age},
70 | person.SEX AS {person.sex}
71 | FROM PERSON person
72 | WHERE person.NAME LIKE :namePattern
73 |
74 | ..
75 | List people = session.getNamedQuery("persons")
76 | .setString("namePattern", namePattern)
77 | .setMaxResults(50)
78 | .list();
79 |
80 | What is the difference between sorted and ordered collection in hibernate?
81 | sorted collection:
82 | A sorted collection is sorting a collection by utilizing the sorting features
83 | provided by the Java collections framework. The sorting occurs in the memory
84 | of JVM which running Hibernate, after the data being read from database using
85 | java comparator. If your collection is not large, it will be more efficient
86 | way to sort it.
87 | order collection :
88 | Order collection is sorting a collection by specifying the order-by clause
89 | for sorting this collection when retrieval. If your collection is very large,
90 | it will be more efficient way to sort it.
91 |
92 | Difference between get() and load()?
93 | If load() can�t find the object in the cache or database, an exception is
94 | thrown. The load() method never returns null. The get() method returns
95 | null if the object can�t be found.
96 | The load() method may return a proxy instead of a real persistent instance.
97 | A proxy is a placeholder that triggers the loading of the real object when it�s
98 | accessed for the first time; we discuss proxies later in this section. On the
99 | other hand, get() never returns a proxy.
100 |
101 | What are the types of Hibernate instance states ?
102 | transient
103 | The instance is not associated with any persistence context. It has no
104 | persistent identity or primary key value.
105 | persistent
106 | The instance is currently associated with a persistence context. It has a
107 | persistent identity (primary key value) and can have a corresponding row in
108 | the database. For a particular persistence context, Hibernate guarantees
109 | that persistent identity is equivalent to Java identity in relation to the
110 | in-memory location of the object.
111 | detached
112 | The instance was once associated with a persistence context, but that
113 | context was closed, or the instance was serialized to another process.
114 | It has a persistent identity and can have a corresponding row in the
115 | database. For detached instances, Hibernate does not guarantee the
116 | relationship between persistent identity and Java identity.
117 |
118 | Hierarchy-to-tables mapping strategies //todo check with reference doc (table per class hierarchy | table per subclass | table per concrete class | implicit polymorphism )
119 | Table per concrete class with implicit polymorphism�Use no explicit
120 | inheritance mapping, and default runtime polymorphic behavior.
121 | You can use exactly one table for each (nonabstract) class.
122 | All properties of a class, including inherited properties, can be mapped to
123 | columns of this table,
124 | Table per concrete class�Discard polymorphism and inheritance relationships
125 | completely from the SQL schema. Table per concrete class with unions.
126 | If your superclass is concrete, then an additional table is needed to hold
127 | instances of that class.
128 | Table per class hierarchy�Enable polymorphism by denormalizing the SQL
129 | schema, and utilize a type discriminator column that holds type information.
130 | An entire class hierarchy can be mapped to a single table.
131 | This table includes columns for all properties of all classes in the hierarchy.
132 | The concrete subclass represented by a particular row is identified by the
133 | value of a type discriminator column.
134 | There is one major problem: Columns for properties declared by subclasses
135 | must be declared to be nullable.
136 | Another important issue is normalization. We�ve created functional
137 | dependencies between nonkey columns, violating the third normal form.
138 | Table per subclass�Represent is a (inheritance) relationships as has a
139 | (foreign key) relationships.
140 | The fourth option is to represent inheritance relationships as relational
141 | foreign key associations. Every class/subclass that declares persistent
142 | properties�including abstract classes and even interfaces�has its own table.
143 | Unlike the table per concrete class strategy we mapped first, the table here
144 | contains columns only for each noninherited property (each property declared
145 | by the subclass itself) along with a primary key that is also a foreign key of
146 | the superclass table.
147 | The primary advantage of this strategy is that the SQL schema is normalized.
148 | Schema evolution and integrity constraint definition are straightforward.
149 | A polymorphic association to a particular subclass may be represented as a
150 | foreign key referencing the table of that particular subclass.
151 | As you can see, this mapping strategy is more difficult to implement by hand�
152 | even ad-hoc reporting is more complex. This is an important consideration if
153 | you plan to mix Hibernate code with handwritten SQL.
154 | Furthermore, even though this mapping strategy is deceptively simple, our
155 | experience is that performance can be unacceptable for complex class
156 | hierarchies. Queries always require either a join across many tables or many
157 | sequential reads.
158 |
159 | What are the Collection types in Hibernate ?
160 | A collection is defined as a one-to-many reference. The simplest collection
161 | type in Hibernate is .This collection is a list of unordered objects and
162 | can contain duplicates. This is similar to java.util.List. The content of a
163 | collection is required for a SQL query. This won�t work until the code is
164 | actually accessed. This process has a benefit that allows the developer to
165 | separate the database access logic from that of the object traversal logic.
166 | This is called lazy collection.
167 | Filtering logic can be applied with lazy collection. This can alter the SQL
168 | which invokes when the actual collection is invoked.
169 | ArrayType,
170 | Constructor: ArrayType(String role, String propertyRef, Class elementClass, boolean isEmbeddedInXML)
171 | BagType,
172 | Constructor: BagType(String role, String propertyRef, boolean isEmbeddedInXML)
173 | CustomCollectionType, A custom type for mapping user-written classes that implement PersistentCollection
174 | Constructor: CustomCollectionType(Class userTypeClass, String role, String foreignKeyPropertyName, boolean isEmbeddedInXML)
175 | IdentifierBagType,
176 | Constructor: IdentifierBagType(String role, String propertyRef, boolean isEmbeddedInXML)
177 | ListType,
178 | Constructor: ListType(String role, String propertyRef, boolean isEmbeddedInXML)
179 | MapType,
180 | Constructor: MapType(String role, String propertyRef, boolean isEmbeddedInXML)
181 | SetType
182 | Constructor: SetType(String role, String propertyRef, boolean isEmbeddedInXML)
183 |
--------------------------------------------------------------------------------
/Framework and Libraries/Java Servlets.txt:
--------------------------------------------------------------------------------
1 | ------------------------------------------------------------------------------------------
2 | Java Servlets
3 | ------------------------------------------------------------------------------------------
4 | 1. What are the classes and interfaces for servlets?
5 | 2. What is the difference between an applet and a servlet?
6 | 3. What is the difference between doPost and doGet methods?
7 | 4. What is the life cycle of a servlet?
8 | 5. Who is loading the init() method of servlet?
9 | 6. What are the different servers available for developing and deploying Servlets?
10 | 7. How many ways can we track client and what are they?
11 | 8. What is session tracking and how do you track a user session in servlets?
12 | 9. What is Server-Side Includes (SSI)?
13 | 10. What are cookies and how will you use them?
14 | 11. Is it possible to communicate from an applet to servlet and how many ways and how?
15 | 12. What is connection pooling?
16 | 13. Why should we go for interservlet communication?
17 | 14. Is it possible to call servlet with parameters in the URL?
18 | 15. What is Servlet chaining?
19 | 16. What is the difference between TCP/IP and UDP?
20 | 17. What is Inet address?
21 | 18. What is Domain Naming Service(DNS)?
22 | 19. What is URL?
23 | 20. What is RMI and steps involved in developing an RMI object?
24 | 21. what is UnicastRemoteObject?
25 | 22. Explain the methods, rebind() and lookup() in Naming class?
26 | 23. What is a Java Bean?
27 | 24. What is a Jar file?
28 | 25. What is BDK?
29 | 26. What is JSP?
30 | 27. What are JSP Directives?
31 | 28. What are Predefined variables or implicit objects?
32 | 29. What are JSP ACTIONS?
33 | 30. How can I set a cookie in JSP?
34 | 31. How can I delete a cookie with JSP?
35 | 32. How are Servlets and JSP Pages related?
36 |
37 |
38 |
39 |
40 |
41 |
42 |
43 |
44 |
45 |
46 |
47 |
48 |
49 |
50 |
51 |
--------------------------------------------------------------------------------
/Framework and Libraries/Java Testing With JUnit.txt:
--------------------------------------------------------------------------------
1 | ------------------------------------------------------------------------------------------
2 | JUnit
3 | ------------------------------------------------------------------------------------------
--------------------------------------------------------------------------------
/Framework and Libraries/Spring.txt:
--------------------------------------------------------------------------------
1 | ----------------- Spring -----------------
2 |
3 | Basic idea of IoC pattern. Benefits.
4 | By applying DI in your projects, you�ll find that your code will
5 | become significantly simpler, easier to understand, and easier to test.
6 | With DI, objects are given their dependencies at creation time
7 | by some third party that coordinates each object in the system. Objects aren�t
8 | expected to create or obtain their dependencies�dependencies are injected into the
9 | objects that need them.
10 | The key benefit of DI�loose coupling. If an object only knows about its
11 | dependencies by their interface (not by their implementation or how they�re
12 | instantiated), then the dependency can be swapped out with a different
13 | implementation without the depending object knowing the difference.
14 | One of the most common ways that a dependency will be swapped out is with a
15 | mock implementation during testing.
16 |
17 | What is Spring configuration file? How does it look like?
18 |
19 |
23 |
24 | [...]
25 |
26 |
27 | [...]
28 |
29 |
30 |
31 | Out of the box bean scopes (singleton, prototype, request, session, global session)
32 | singleton Scopes the bean definition to a single instance per Spring container (default).
33 | prototype Allows a bean to be instantiated any number of times (once per use).
34 | request Scopes a bean definition to an HTTP request. Only valid when used with a
35 | web-capable Spring context (such as with Spring MVC).
36 | session Scopes a bean definition to an HTTP session. Only valid when used with a
37 | web-capable Spring context (such as with Spring MVC).
38 | global-session Scopes a bean definition to a global HTTP session. Only valid when used in a portlet context.
39 |
40 | What are the types of Dependency Injection Spring supports?
41 | Injecting through constructors
42 | Injecting into bean properties
43 |
44 | Autowiring. Types of autowiring.
45 | byName Attempts to match all properties of the autowired bean with beans
46 | that have the same name (or ID) as the properties. Properties for which there�s
47 | no matching bean will remain unwired.
48 | byType Attempts to match all properties of the autowired bean with beans
49 | whose types are assignable to the properties. Properties for which there�s no
50 | matching bean will remain unwired.
51 | constructor Tries to match up a constructor of the autowired bean with
52 | beans whose types are assignable to the constructor arguments.
53 | autodetect Attempts to apply constructor autowiring first. If that fails,
54 | byType will be tried.
55 |
56 | What are inner beans.
57 | Inner beans are beans that are defined within the scope of another bean.
58 | Note that the inner beans don�t have an id attribute set. Though it�s perfectly legal
59 | to declare an ID for an inner bean, it�s not necessary because you�ll never refer to the
60 | inner bean by name. This highlights the main drawback of using inner beans: they
61 | can�t be reused. Inner beans are only useful for injection once and can�t be referred
62 | to by other beans.
63 | You may also find that using inner-bean definitions has a negative impact on the
64 | readability of the XML in the Spring context files.
65 |
66 | What modules does Spring Framework have?
67 | Spring Framework Runtime
68 | DataAccess/Integration
69 | JDBC ORM OXM JMS
70 | Transactions
71 | Web (MVC/Remoting)
72 | Web Servlet Portlet Struts
73 | AOP Aspects Instumentation
74 | Core Container
75 | Beans Core Context ExpressionLanguage
76 | Test
77 | http://static.springsource.org/spring/docs/3.0.x/spring-framework-reference/html/overview.html
78 |
79 | Could you please tell us about Spring? What is the most important feature(s) of Spring?
80 | Lightweight and minimally invasive development with plain old Java objects(POJOs)
81 | Loose coupling through dependency injection and interface orientation
82 | Declarative programming through aspects and common conventions
83 | Boilerplate reduction through aspects and templates
84 |
85 | What are ORM�s Spring supports ?
86 | Spring provides support for several persistence frameworks, including Hibernate,
87 | iBATIS, Java Data Objects (JDO), and the Java Persistence API (JPA).
88 |
89 | How to integrate Spring and Hibernate using HibernateDaoSupport?
90 | not reccomended http://stackoverflow.com/questions/5104765/hibernatedaosupport-is-not-recommended-why
91 | 1)configure session factory
92 |
93 |
94 |
95 |
96 |
97 | org.hibernate.dialect.HSQLDialect
98 |
99 |
100 |
101 | 2)create dao class by extending HibernateDaoSupport
102 | class ExampleDao extends HibernateDaoSupport {
103 | ...
104 | List bb = (List)getHibernateTemplate().find("from cc");
105 | }
106 |
107 |
--------------------------------------------------------------------------------
/Images/Java Collections Hierarchy.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/svozniuk/java-interviews/3c1c66b0cdcf35092f05faf178248d5e8365220c/Images/Java Collections Hierarchy.jpg
--------------------------------------------------------------------------------
/Images/Java Collections.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/svozniuk/java-interviews/3c1c66b0cdcf35092f05faf178248d5e8365220c/Images/Java Collections.jpg
--------------------------------------------------------------------------------
/Java Core/JVM Internals.txt:
--------------------------------------------------------------------------------
1 | ------------------------------------------------------------------------------------------
2 | JVM Internals
3 | ------------------------------------------------------------------------------------------
4 |
5 | Questions taken from
6 |
7 | http://www.roseindia.net/java/java-virtual-machine.shtml
8 | http://www.interviewjava.com/2007/04/inside-java-virtual-machine.html
9 | http://www.javabeat.net/2010/08/jvmjrejava-compiler-interview-questions/2/
10 |
11 | Answers taken from
12 |
13 | http://www.artima.com/insidejvm/ed2/jvm.html
14 |
15 | ------------------------------------------------------------------------------------------
16 |
17 | 1. What is Java Virtual Machine?
18 | 2. Memory Management with JVM ?
19 | 3. Explain the Difference amongst JVM Specification, JVM Implementation, JVM Runtime.
20 | 4. Why is the source file named after the class?
21 | 5. Which class should be compiled first?
22 | 6. What are the steps in compiling a class?
23 | 7. Where is my compiled class file?
24 | 8. How can I ensure my compiler will locate the SAX package?
25 | 9. What are undefined and undeclared variables?
26 | 10. Why doesn’t the compiler warn about stack overflow problems?
27 | 11. What is a Java Virtual Machine (JVM)?
28 | 12. What does a JVM consist of?
29 | 13. What is a class loader and what is its responsibilities?
30 | 14. What is heap and stack?
31 | 15. How is your Java program executed inside JVM?
32 | 16. What is Java class file's magic number?
33 | 17. How JVM performs Thread Synchronization?
34 | 18. If your program is I/O bound or running in native methods, do these activities engage JVM?
35 | 19. What is the difference between interpreted code and compiled code?
36 | 20. Why Java based GUI intensive program has performance issues?
37 | 21. What is 64 bit Java ?
38 | 22. What is the difference between JVM and JRE?
39 | 23. Explain the processes performed by java virtual machine, i.e. loading, linking, initialization.
40 | 24. What is javap?
41 | 25. Explain the purpose of garbage collection that the JVM uses
42 | 26. How JVM performs Garbage Collection?
43 | 27. How to profile heap usage?
44 | Use jconsole, hprof, jstat for example.
45 | 28. What will you do if VM exits while printing "OutOfMemoryError" and increasing max heap size doesn't help?
46 | Same as above
47 | 29. Should one pool objects to help Garbage Collector? Should one call System.gc() periodically?
48 | No.
49 | 30. An application has a lot of threads and is running out of memory, why?
50 | 31. Types of GC
51 | 32. Generations of heap space
--------------------------------------------------------------------------------
/Java Core/Java Applets.txt:
--------------------------------------------------------------------------------
1 | ------------------------------------------------------------------------------------------
2 | Java Applets
3 | ------------------------------------------------------------------------------------------
4 |
5 | 1. What is the Locale class?
6 | 2. Can applets communicate with each other?
7 | 3. Can an unreachable object become reachable again?
8 | 7. What is an applet?
9 | 8. What is the difference between applications and applets?
10 | 9. How does applet recognize the height and width?
11 | 10. When do you use codebase in applet?
12 | 11. What is the lifecycle of an applet?
13 |
--------------------------------------------------------------------------------
/Java Core/Java Assertions.txt:
--------------------------------------------------------------------------------
1 | ------------------------------------------------------------------------------------------
2 | Java Assertions
3 | ------------------------------------------------------------------------------------------
--------------------------------------------------------------------------------
/Java Core/Java Basics.md:
--------------------------------------------------------------------------------
1 | Java Basics
2 | -----------
3 |
4 | 1. ****What is the difference between an Interface and an Abstract class?****
5 |
6 | Both define an interface that has to be implemented. Abstract class can contain concrete methods as well as abstract. Abstract class can contain regular class fields. Interface can contain only public static final fields.
7 |
8 | 2. **What is the purpose of garbage collection in Java, and when is it used?**
9 |
10 | GC in Java is the mechanism that keeps track of memory and objects residing in memory. GC collects the object when it is no longer needed (usually when no references to the object are available).
11 |
12 | 3. **What is the difference between a constructor and a method?**
13 |
14 | We can say that constructor is a special kind of method that instantiates the object. The main differences are
15 |
16 | * Special treatment of constructors when they are called (memory allocation, superclass constructors chain)
17 | * More caution is required when writing a constructor
18 |
19 | 4. **State the significance of public, private, protected, default modifiers both singly and in combination and state the effect of package relationships on declared items qualified by these modifiers.**
20 |
21 | * public
22 | class -- accessible from anywhere. Can be subclassed by anyone (if not declared final)
23 | method -- accessible from anywhere. Can be overriden in subclasses.
24 | variable -- accessible from anywhere. Usually not a good practice except for the constants
25 | inner class -- accessible from anywhere.
26 | nested class -- accessible from anywhere.
27 | * private
28 | class -- only for inner classes.
29 | method -- accessible only from the class where it is declared. Cannot be overridden
30 | variable -- accessible only from the class where it is declared
31 | inner class -- same
32 | nested class -- same
33 | * protected
34 | class -- only for inner classes
35 | method -- accessible from the same package or from any subclass
36 | variable -- same
37 | inner class -- same
38 | nested class -- can be written but doesn't make sense (protected static!?)
39 | * default (no access modifier)
40 | class -- only this package and subclasses in this package
41 | method -- same
42 | variable -- same
43 | inner class -- same
44 | nested class -- same
45 |
46 | 5. **What is an abstract class?**
47 |
48 | An abstract class is a java class that has one or more abstract methods (no body). Abstract classes cannot be instantiated. Abstract class defines an interface that has to be implemented by all its subclasses.
49 |
50 | 6. **What is static in java?**
51 |
52 | static is Java Language keyword.
53 | a) When used with a method defines a method of a class.
54 | b) When used with a field defines a class field.
55 | c) When used on an nested class declaration defines a static nested class.
56 | d) Also can be used for static initialization block.
57 | e) Can be used as a static initialization block
58 |
59 | 7. **What is final?**
60 |
61 | final is Java Language keyword.
62 | a) When used with a method protects it from being overridden in subclasses. Done for security and/or performance reasons.
63 | b) When used with a field means that the value stored in the field cannon be changed after initialization. Not to be confused with immutability of the object.
64 | c) When used with a class declaration protects it from being subclassed. Done for security and/or performance reasons. Also for immutability. Many of Java core classes are final (e.g. String)
65 |
66 | 8. **How can one prove that the array is not null but empty using one line of code?**
67 |
68 | array == null ? xx : array.length == 0
69 | if the array is instance field it's initialized to null. And this code works.
70 | if the array is local variable the compiler will generate an error if it has not been initialized
71 |
72 | 9. **What environment variables do I need to set on my machine in order to be able to run Java programs?**
73 |
74 | CLASSPATH, PATH and/or JAVA_HOME
75 |
76 | 10. **Do I need to import java.lang package any time? Why ?**
77 |
78 | No. It is imported by default
79 |
80 | 11. **Can I import same package/class twice? Will the JVM load the package twice at runtime?**
81 |
82 | Yes you can declare import twice in the import section.
83 | No it will not be loaded twice at runtime.
84 |
85 | 12. **What is Overriding?**
86 |
87 | Changing method behavior in the subclasses.
88 |
89 | 13. **What are different types of inner classes?**
90 |
91 | if declared with static -- it's nested class. Nested classes are fairly independent and treated as top-level classes. But the constructor call is different.
92 | To construct one: new OuterClassNeme.InnerClassName().
93 |
94 | if declared without static -- inner class. Each instance of inner class can only exist within an instance of the outer class.
95 | To construct one: instanceOfOuterClass.new InnerClassName()
96 |
97 | local class -- declared and visible only within a block of code
98 | anonymous -- same, but they don't even have a name.
99 |
100 | 14. **Are the imports checked for validity at compile time? e.g. will the code containing an import such as java.lang.ABCD compile?**
101 |
102 | Yes, they are checked. No it won't compile.
103 |
104 | 15. **Does importing a package imports the sub-packages as well? e.g. Does importing com.MyTest.* also** import com.MyTest.UnitTests.*?
105 |
106 | No. This declaration will only import classes located directly in com.MyTest package.
107 |
108 | 16. **What is the difference between declaring a variable and defining a variable?**
109 |
110 | Declaring is declaring. Defining is assigning some value to the declared vaiable.
111 |
112 | 17. **What is the default value of an object reference declared as an instance variable?**
113 |
114 | null
115 |
116 | 18. **Can a top level class be private or protected?**
117 |
118 | No. It is only allowed to be public or to have default access modifier.
119 |
120 | 19. **What type of parameter passing does Java support?**
121 |
122 | Java passes all parameters by values. The references to objects are passed by values.
123 |
124 | 20. **Primitive data types are passed by reference or pass by value?**
125 |
126 | See above
127 |
128 | 21. **Objects are passed by value or by reference?**
129 |
130 | See above
131 |
132 | 22. **What are pass by reference and pass by value?**
133 |
134 | Pass by reference -- a reference to the Object is passed to the method.
135 | Pass by value -- a copy of the actual value of the Object is passed to the method. The method is then unable to modify the original Object. (Not true in Java. In Java references to objects are passed by value)
136 |
137 | 23. **Give a simplest way to find out the time a method takes for execution without using any profiling tool?**
138 |
139 | System.currentTimeMillis() in the beginning and end of the method
140 |
141 | 24. **Is Empty .java file a valid source file?**
142 |
143 | Yes it is.
144 |
145 | 25. **Can a .java file contain more than one java classes?**
146 |
147 | Yes it can. It has to contain only one top level public java class but it can contain any number of inner, anonymous and top level classes with default access modifier.
148 |
149 | 26. **Is String a primitive data type in Java?**
150 |
151 | No. String is an Object. An immutable one.
152 |
153 | 27. **Is main a keyword in Java?**
154 |
155 | No. main is the name of the method that is treated in special way if declared properly.
156 |
157 | 28. **Is next a keyword in Java?**
158 |
159 | No. next() is method of Iterator or Enumeration interface.
160 |
161 | 29. **Is delete a keyword in Java?**
162 |
163 | No. delete is not a keyword. And I cannot even remember a class that has a method called delete(). Rather remove()
164 |
165 | 30. **Is exit a keyword in Java?**
166 |
167 | No. exit() is a method of java.lang.System class
168 |
169 | 31. **What happens if you dont initialize an instance variable of any of the primitive types in Java?**
170 |
171 | It gets assigned the default value. 0 for int and long, 0.0 for float and double, false for boolean. Though I tried to compile a class where variables were not initialized and it didn't compile.
172 |
173 | 32. **What are the different scopes for Java variables?**
174 |
175 | static fields, instance fields, method parameters, local variables
176 |
177 | 33. **What is the default value of the local variables?**
178 |
179 | No default value. Default values are assigned to instance fields. Local variables have to be explicitly initialized.
180 |
181 | 34. **Does garbage collection guarantee that a program will not run out of memory?**
182 |
183 | No. Not at all. Example: recursive call. Or just create lots of objects until you get OutOfMemoryError (or is it an exception?)
184 |
185 | 35. **What is the purpose of finalization?**
186 |
187 | Free up the resources. (e.g. close connections and streams, release a lock etc)
188 |
189 | 36. **Can a public class MyClass be defined in a source file named YourClass.java?**
190 |
191 | no. Unless it is a nested class public class.
192 |
193 | 37. **What will be the output of the following statement? System.out.println ("1" **+ 3);**
194 |
195 | 13
196 |
197 | 38. **What will be the default values of all the elements of an array defined as an instance variable?**
198 |
199 | All elements will be initialized to default value of corresponding type.
200 |
201 | 39. **Length in bytes for primitive types**
202 |
203 | | Primitive type| length in bytes | Comment |
204 | | :------------ |:----------------:| ---------------------------------------:|
205 | | boolean | 1 bit | saved as 4 bytes; 1 byte in an array |
206 | | char | 2 bytes | unsigned |
207 | | byte | 1 byte | |
208 | | short | 2 bytes | |
209 | | int | 4 bytes | |
210 | | long | 8 bytes | |
211 | | float | 4 bytes | |
212 | | double | 8 bytes | |
213 |
214 |
215 | 40. **Contract between equals() and hashCode()**
216 |
217 | if a.equals(b) returns true then a.hashCode() == b.hashCode() is also true. Note that equal hashCode doesn't mean anything.
218 |
219 | 41. **What different between StringBuffer and StringBuilder?**
220 |
221 | StringBuilder -- new. StringBuffer -- old. StringBuffer -- synchronized. Where possible use StringBuilder.
222 | Both represent mutable sequence of characters.
223 |
224 | 42. **What internal methods of String do you know?**
225 |
226 | static methods of String class: valueOf
227 | indexOf, lastIndexOf, replace, contains, startsWith, endsWith, substring
228 | matches, split
229 | equals, isEmpty
230 |
231 | 43. **Purpose, types and creation of nested classes**
232 |
233 | Types of nested classes see above.
234 | Purpose:
235 | If a package-private top-level class (or interface) is used by only one class, consider making the top-level class a private nested class of the sole class that uses. This reduces its accessibility from all the classes in its package to the one class that uses it. But it is far more important to reduce the accessibility of a gratuitously public class than of a package-private top-level class: the public class is part of the package’s API, while the package-private top-level class is already part of its implementation.
236 | One common use of a static member class is as a public helper class, useful only in conjunction with its outer class
237 | If an instance of a nested class can exist in isolation from an instance of its enclosing class, then the nested class must be a static member class: it is impossible to create an instance of a nonstatic member class without an enclosing instance.
238 | One common use of a nonstatic member class is to define an Adapter that allows an instance of the outer class to be viewed as an instance of some unrelated class.
239 | For example, implementations of the Map interface typically use nonstatic member classes to implement their collection views, which are returned by Map’s keySet, entrySet, and values methods. Similarly, implementations of the collection interfaces, such as Set and List, typically use nonstatic member classes to implement their iterators.[Effective Java]
240 | A common use of private static member classes is to represent components of the object represented by their enclosing class. For example, consider a Map instance, which associates keys with values. Many Map implementations have an internal Entry object for each key-value pair in the map.
241 | One common use of anonymous classes is to create function objects on the fly. For example, the sort method invocation sorts an array of strings according to their length using an anonymous Comparator instance.
242 | To recap, there are four different kinds of nested classes, and each has its place. If a nested class needs to be visible outside of a single method or is too long to fit comfortably inside a method, use a member class. If each instance of the member class needs a reference to its enclosing instance, make it nonstatic; otherwise, make it static. Assuming the class belongs inside a method, if you need to create instances from only one location and there is a preexisting type that characterizes the class, make it an anonymous class; otherwise, make it a local class.
243 |
244 | 44. **What does it mean that an object or a class is mutable or immutable?**
245 |
246 | Immutability: the state of the object doesn't change
247 |
248 | 45. **Is it enough to define this class as final? To make this class immutable?**
249 |
250 | No. If the class is declared final it only means that it cannot be subclassed. If the instance of the class is declared to be final it only means that the reference will not change. The inner state of the object in both cases can change.
251 |
252 | 46. **Besides “String” do you know any other immutable classes?**
253 |
254 | BigDecimal, BigInteger all classes that correspond to primitive types
255 | java.awt.Color
256 |
257 | 47. **Increasing/descreasing of methods visibility (inheritence)**
258 |
259 | The main rule is that visibility cannot be reduced in the subclass
260 |
261 | 48. **You need to create the string, which contains 1,000,000 **random numbers, comma separated. How would** you do that, considering performance?
262 |
263 | I would use StringBuilder class
264 |
265 | 49. **Garbage collection principles**
266 |
267 | The garbage collector first performs a task called marking. The garbage collector traverses the application graph, starting with the root objects; those are objects that are represented by all active stack frames and all the static variables loaded into the system. Each object the garbage collector meets is marked as being used, and will not be deleted in the sweeping stage. The sweeping stage is where the deletion of objects take place.
268 |
269 | 50. **Java de-compiler, when it could be helpful except studying, learning, stealing**
270 |
271 | Recovering lost sources?TODO????????
272 |
273 | 51. **How is the virtual space divided in Java?**
274 |
275 | http://stackoverflow.com/questions/1262328/how-is-the-java-memory-pool-divided
276 | http://docs.oracle.com/javase/6/docs/technotes/guides/management/jconsole.html
277 |
278 | 52. **What difference between float and BigDecimal. How they store the data?**
279 |
280 | float is floating point number and can loose precision during the computations.
281 | BigDeciamal is fixed point number. The computations (which type of computations?) are guaranteed to maintain the needed precision.
282 | Internally BigDecimal consists of an arbitrary precision integer unscaled value and a 32-bit integer scale
283 | If no rounding mode is specified and the exact result cannot be represented, an exception is thrown
284 |
285 | 53. **What is deep copy of a Java object?**
286 |
287 | Deep copy creates a copy of the object including deep copies of all its fields.
288 |
289 | 54. **What are utilities for JVM monitoring? What is Jconsole?**
290 |
291 | From http://docs.oracle.com/javase/6/docs/technotes/tools/
292 |
293 | jvisualvm -- A graphical tool that provides detailed information about the Java technology-based applications (Java applications) while they are running in a Java Virtual Machine. Java VisualVM provides memory and CPU profiling, heap dump analysis, memory leak detection, access to MBeans, and garbage collection.See Java VisualVM for more information.
294 |
295 | jconsole -- A JMX-compliant graphical tool for monitoring a Java virtual machine. It can monitor both local and remote JVMs. It can also monitor and manage an application.
296 |
297 | jps -- Experimental: JVM Process Status Tool - Lists instrumented HotSpot Java virtual machines on a target system.
298 |
299 | jstat -- Experimental: JVM Statistics Monitoring Tool - Attaches to an instrumented HotSpot Java virtual machine and collects and logs performance statistics as specified by the command line options.
300 |
301 | jstatd -- Experimental: JVM jstat Daemon - Launches an RMI server application that monitors for the creation and termination of instrumented HotSpot Java virtual machines and provides a interface to allow remote monitoring tools to attach to Java virtual machines running on the local system.
302 |
303 | jhat -- Experimental - Heap Dump Browser - Starts a web server on a heap dump file (eg, produced by jmap -dump), allowing the heap to be browsed.
304 |
305 | jmap -- Experimental - Memory Map for Java - Prints shared object memory maps or heap memory details of a given process or core file or a remote debug server.
306 |
307 | jsadebugd -- Experimental - Serviceability Agent Debug Daemon for Java - Attaches to a process or core file and acts as a debug server.
308 |
309 | jstack -- Experimental - Stack Trace for Java - Prints a stack trace of threads for a given process or core file or remote debug server.
310 |
311 | Never used any of these tools yet. :(
312 |
313 | 55. **How and in what cases we need to configure sizes of memory areas in Java?**
314 |
315 | In case of getting OutOfMemoryError: Java heap space. What other cases?
316 | JVM parameter -Xmx###m where ### is number of megabytes you need for the JVM.
317 | -Xms###m to set the initial heap size
318 | More info on this topic can be found here: http://blog.codecentric.de/en/2011/03/java-memory-configuration-and-monitoring-3rd-act/
319 |
320 | 56. **What is an Object and how do you allocate memory to it?**
321 |
322 | Object is the base class in Java. Object in general case is an instance of a class. The memory is allocated when new operator is executed. The minimum size is 8 bytes (thats what you get if you call new Object). Each primitive data type takes 4 bytes, except double and long, which take 8 bytes.
323 |
324 | 58. **What are methods and how are they defined?**
325 |
326 | Method is an abstraction that defines how a specific computation has to be carried out. Method "abstracts away" the code it contains.
327 |
328 | 59. **What is the use of bin and lib in JDK?**
329 |
330 | bin -- all java binaries: javac, java, appletviewer, jconsole...
331 | lib -- java libraries
332 |
333 | 60. **What is casting?**
334 |
335 | changing the type of the object.
336 |
337 | 61. **In how many ways can an argument be passed to a subroutine and explain them?**
338 |
339 | only one. By value. See above
340 |
341 | 62. **What is the difference between an argument and a parameter?**
342 |
343 | parameter -- abstract. argument -- concrete value of the parameter.
344 | parameters of the function are defined when the function is declared
345 | arguments of the funciton are defined when it is called
346 |
347 | 63. **What is final, finalize() and finally?**
348 |
349 | final -- Java keyword, see above
350 | finalize() -- gets called before the object is GC-ed
351 | finally -- Java keyword used in exception handling.
352 |
353 | 64. **What is UNICODE?**
354 |
355 | See info on Unicode here http://docs.oracle.com/javase/1.5.0/docs/api/java/lang/Character.html
356 |
357 | 65. **What is finalize() method?**
358 |
359 | See above.
360 |
361 | 66. **What are Transient and Volatile Modifiers?**
362 |
363 | Transient signifies that the field is not part of the object state (e.g. it's some derieved value or some cache). Transient fields are not present in serialized representation of the object.
364 | If field is declared with volatile keyword then any thread that reads the field will see the most recently written value [Effective Java Item 66]
365 |
366 | 67. **What is difference between overloading and overriding?**
367 |
368 | overloading -- adding a method with the same name but different signature
369 | overriding -- changing the method implementation in the subclass
370 |
371 | 68. **What is meant by Inheritance and what are its advantages?**
372 |
373 | Inheritance is one of principles of OOP. It allows to create class hierarchies. Classes can inherit methods and properties from the base classes thus increasing code reuse.
374 |
375 | 69. **What is the difference between this() and super()?**
376 |
377 | this() calls the constructor of current class.
378 | super() calls the superclass constructor
379 | super() has to be the first statement of subclass constructor;
380 | this and super are references to the current object and to current object treated as superclass.
381 | this.new Something() has to be used to create inner classes
382 |
383 | 70. **What is the difference between superclass and subclass?**
384 |
385 | Obvious.
386 |
387 | 71. **What modifiers may be used with top-level class?**
388 |
389 | only public or default (package-private)
390 |
391 | 72. **What is a package?**
392 |
393 | In Java package is a mechanism to oragnize classes into modules.
394 |
395 | 73. **What is a reflection package?**
396 |
397 | Not sure the question is clearly stated. What I would answer is pasted from javadoc of java.lang.reflect
398 | Provides classes and interfaces for obtaining reflective information about classes and objects. Reflection allows programmatic access to information about the fields, methods and constructors of loaded classes, and the use reflected fields, methods, and constructors to operate on their underlying counterparts on objects, within security restrictions.
399 |
400 | 74. **What is the difference between Integer and int?**
401 |
402 | Integer is a wrapper class for int primitive type. Integer can be used in generic collections whereas int cannot. Also contains a number of utility methods.
403 |
404 | 75. **What is a cloneable interface and how many methods does it contain?**
405 |
406 | Cloneable -- is a marker interface and it doesn't contain any methods. It determines the behavior of Object’s protected clone implementation: if a class implements Cloneable, Object’s clone method returns a field-by-field copy of the object; otherwise it throws CloneNotSupportedException
407 |
408 | 76. **Can you have an inner class inside a method and what variables can you access?**
409 |
410 | You can create a local or anonymous class inside the method. It can access only final variables.
411 |
412 | 77. **What is the difference between String and StringBuffer?**
413 |
414 | 78. **What is the difference between a while statement and a do statement?**
415 |
416 | do is guaranteed to execute at least once.
417 |
418 | 79. **What is the difference between static and non-static variables?**
419 |
420 | a) The way they are initialized. Static are initalized when the class is loaded. Non-static -- when it's instantiated.
421 | b) Non-static belong to the instance of an object while static are class variables.
422 | c) Static are accessed using ClassName.varName
423 |
424 | 80. **How does Java handle integer overflows and underflows?**
425 |
426 | It goes down to the MIN_INT value in case of overflow and to MAX_INT in case of overflow
427 |
428 | Main method
429 | ---------------
430 | 1. **Can an application have multiple classes having main method?**
431 |
432 | Yes it can. But only one main method will be used as the entrance point for the program.
433 |
434 | 2. **Can I have multiple main methods in the same class?**
435 |
436 | No, if you mean public static void main(String[] args).
437 | Yes, if you mean a method with a name "main" and any other signature
438 |
439 | 3. **What if the main method is declared as private?**
440 |
441 | The class will compile. But the method cannot be used as the entrance point
442 |
443 | 4. **What if the static modifier is removed from the signature of the main method?**
444 |
445 | It becomes an instance method. No longer an entrance point but just a valid regular method.
446 |
447 | 5. **What if I write static public void instead of public static void?**
448 |
449 | Nothing happens. Class compiles. Method runs.
450 |
451 | 6. **What if I do not provide the String array as the argument to the method?**
452 |
453 | You just define a static method called "main" with no parameters. It cannot be used as entrance point.
454 |
455 | 7. **What is the first argument of the String array in main method?**
456 |
457 | These are the parameters passed to the program from command line.
458 |
459 | 8. **If I do not provide any arguments on the command line, then the String array of Main method will be** empty or null?
460 |
461 | Array of size 0
462 |
463 | 9. **Can main method be declared final?**
464 |
465 | Yes it can be declared as final.
466 |
--------------------------------------------------------------------------------
/Java Core/Java Collections.txt:
--------------------------------------------------------------------------------
1 | ------------------------------------------------------------------------------------------
2 | Collections
3 | ------------------------------------------------------------------------------------------
4 |
5 | 1. Draw Collections Framework Class Diagram
6 |
7 | interface Iterable
8 | interface Collection extends Iterable
9 | interfaces List, Queue, Set extend Collection
10 | interface SortedSet extends Set
11 | interface Map
12 | interface SortedMap extends Map
13 | classes ArrayList, Vector, Stack, LinkedList implement List
14 | classes HashSet, LinkedHashSet implement Set
15 | class TreeSet implements SortedSet
16 | classes HashMap, WeakHashMap, LinkedHashMap implement Map
17 | class TreeMap implements SortedMap
18 | utility classes Collections and Arrays
19 |
20 | 2. What is HashMap and Map?
21 |
22 | Map is an interface. Contains methods to manipulate Key-Value based collections. The main methods of Map interface are put(K,V), get(K), Collection values(), Set keySet(), containsKey(), containsValue()
23 | HashMap is one of implementations of the Map interface based on hashcodes of objects used as keys.
24 |
25 | 3. Difference between HashMap and HashTable? Can we make hashmap synchronized?
26 |
27 | Both implement Map interface. HashTable is synchronized. It is recommended to use HashMap wherever possible. HashTable doesn't allow null keys and values. HashMap allows one null key and any number of null values.
28 | We can make it synchronized
29 | Map m = Collections.synchronizedMap(new HashMap());
30 |
31 | 4. Difference between Vector and ArrayList?
32 |
33 | Both implement List interface. ArrayList is not synchronized.
34 |
35 | 5. What is an Iterator?
36 |
37 | It is an interface that contains three methods: next(), boolean hasNext(), void remove()
38 | It allows to iterate over the collection
39 | If the class implements iterator then it can be used in foreach loop
40 |
41 | 6. List vs Set vs Map. Purposes and definitions.
42 |
43 | All three are interfaces.
44 |
45 | List -- storing values in specified order. Provides methods to get the element by its position get(i), finding element, ListIterator. Known implementations: ArrayList, Vector, LinkedList. List should be used when the order in which the elements are stored matters.
46 |
47 | Set -- storing only different objects and at most one null element. Known implementations: TreeSet (iterate over the elements in order defined by Comparator, or if the elements implement comparable; provides log(n) performance for basic operations), HashSet -- stores values in buckets defined by their hashcodes. Each bucket is a singly linked list. Provides constant time performance for basic operations. LinkedHashSet
48 |
49 | Map -- for storing key-value pairs. Map cannot contain duplicate keys. Provides three collection views: set of keys, collection of values, set of key-value mappings. Know implementations HashMap, EnumMap, TreeMap, LinkedHashMap, WeakHashMap.
50 |
51 | 7. Pros and cons of ArrayList and LinkedList
52 |
53 | ArrayList -- fast random access.
54 | LinkedList -- slow random access. Implements Queue interface. Fast deletion of the element.
55 | If lots of random reads is anticipated use ArrayList.
56 | If lots of iterations over the whole list and lots of add/delete -- use LinkedList.
57 |
58 | 8. TreeSet vs LinkedHashSet
59 |
60 | LinkedHashSet is backed by LinkedHashMap. LinkedHashMap is backed by doubly linked list to enforce ordering on the elements contained in the Map.
61 | If the ordering of the elements in the Set matters to you but you don't want to use a comparator you may use LinkedHashSet since it will enforce ordering in which the elements were added to the set. Otherwise use TreeSet
62 |
63 | 9. What are relationships between equals and hash codes?
64 |
65 | See in Java Basics.
66 |
67 | 10. What are the advantages of ArrayList over arrays ?
68 |
69 | 1. ArrayList comes with a number of utility methods (e.g. contains, remove, addAll)
70 | 2. Type safety
71 | 3. Dynamic sizing
72 | On the other hand arrays are a little bit faster and take less memory (packing). Arrays are also able to contain values of primitive types while ArrayList can only contain Objects.
73 |
74 | 11. Principle of storing data in a hashtable
75 |
76 | HashSet. add(element) -> element.hashCode() -> mod bucketsCount -> store
77 | HashMap. add(key, value) -> key.hashCode() -> mod bucketsCount -> store(value)
78 |
79 | 12. Differences between Hashtable, ConcurrentHashMap and Collections.synchronizedMap()
80 |
81 | ConcurrentHashMap allows concurrent modification of the Map from several threads without the need to block them. Collections.synchronizedMap(map) creates a blocking Map which will degrade performance, albeit ensure consistency (if used properly).
82 | Use the second option if you need to ensure data consistency, and each thread needs to have an up-to-date view of the map. Use the first if performance is critical, and each thread only inserts data to the map, with reads happening less frequently.
83 |
84 | 13. How are hash codes computed?
85 |
86 | if hashCode() method is defined then it is called to calculate the hashcode
87 | if its not defined the default implementation in Object class does the following:
88 |
89 | public int hashCode() {
90 | return VMMemoryManager.getIdentityHashCode(this);
91 | }
92 |
93 | 14. Is it possible that hash code is not unique?
94 |
95 | It's totally possible. Actually a totally valid hashCode() function could look like this
96 |
97 | int hashCode(){ return 57; }
98 |
99 | 15. Can we put two elements with equal hash code to one hash map?
100 |
101 | Yes we can. The hashcode of objects doesn't matter. Only the hashcode of keys. But even if you want to put keys with the same hashcode it will be ok since it just means that key-value pairs will be put into the same bucket
102 |
103 | 16. Iterator and modification of a List. ConcurentModificationException.
104 |
105 | The iterators returned by this class's iterator method are fail-fast: if the set is modified at any time after the iterator is created, in any way except through the iterator's own remove method, the iterator will throw a ConcurrentModificationException. Thus, in the face of concurrent modification, the iterator fails quickly and cleanly, rather than risking arbitrary, non-deterministic behavior at an undetermined time in the future.
106 |
107 | Note that the fail-fast behavior of an iterator cannot be guaranteed as it is, generally speaking, impossible to make any hard guarantees in the presence of unsynchronized concurrent modification. Fail-fast iterators throw ConcurrentModificationException on a best-effort basis. Therefore, it would be wrong to write a program that depended on this exception for its correctness: the fail-fast behavior of iterators should be used only to detect bugs.
108 |
109 | 17. What is the significance of ListIterator? What is the difference b/w Iterator and ListIterator?
110 |
111 | ListIterator allows to perform iteration both ways (first-->last and last-->first)
112 | From JavaDoc: ListIterator is an iterator for lists that allows the programmer to traverse the list in either direction, modify the list during iteration, and obtain the iterator's current position in the list
113 |
114 | 18. What is the Collections API?
115 |
116 | See above
117 |
118 | 19. How can we access elements of a collection?
119 |
120 | Depends on the collection type. In general: using an iterator, getting by index, getting by key, using iterator on a view
121 |
122 | 20. What’s the difference between a queue and a stack?
123 |
124 | In Java Queue is an interface and has a number of implementations. Stack is a class derieved from Vector class.
125 | The Queue interface contains methods to enqueue and dequeue elements: offer(), poll(). Also contains methods to see the first element in the queue: peek(). The queue ordering is not neccessairly FIFO. It can be based on the comparator (PriorityQueue)
126 | The Stack contains methods to add and remove elements to/from a stack. If used correctly enforces LIFO policy. Contains methods push(), pop(), peek(). The problem with Java stack implementation is that it contains all the methods from Vector class which can lead to violation of LIFO policy.
127 |
128 | 21. What is the Properties class?
129 |
130 | Property class is designed to hold properties (i.e. pairs -- property name (key) and property value). The two main methods of Properties class is getProperty(String name) and setProperty(String name, String value). Properties class extends HashTable
131 |
132 | 22. Which implementation of the List interface provides for the fastest insertion of a new element into the middle of the list?
133 |
134 | LinkedList. It only requires 4 assignments.
135 | Before: ... <--> A <--> B <--> ...
136 | After: ... <--> A <--> C <--> B <--> ... . A changes one reference, B changes one reference, C assigns two references.
137 |
138 | 23. How can we use hashset in collection interface?
139 |
140 | I'm not sure I understand this question fully. HashSet implements Set interface which in turn extends the Collection interface. Thus HashSet is a valid class to be used everywhere where Collection interface is required.
141 |
142 | 25. Can you limit the initial capacity of vector in java?
143 |
144 | I'm not sure if limit is correct word to be used in this question. One can just set the initial capacity of the Vector. Well you could say that you are putting lower limit on the size of the Vector.
145 |
146 | 26. What method should the key class of Hashmap override?
147 |
148 | equals() and hashCode().
149 |
150 | 27. What is the difference between Enumeration and Iterator?
151 |
152 | Enumeration is an interface similar to Iterator. But it doesn't have remove() method. Enumeration acts as Read-only interface, because it has the methods only to traverse and fetch the objects, where as using Iterator we can manipulate the objects also like adding and removing the objects
153 |
154 | 28. Collections class and Arrays class
155 |
156 | The Collections class contains a number of factory methods for creating unmodifiable views or synchronized wrappers of collections, as well as utility methods such as sort, shuffle, reverse
157 |
158 | The Arrays class contains a factory method that take an array as input and return a List based on this array (Arrays.asList()). Also contains methods to sort, search, fill and print arrays
159 |
--------------------------------------------------------------------------------
/Java Core/Java Concurrency.txt:
--------------------------------------------------------------------------------
1 | ------------------------------------------------------------------------------------------
2 | Concurrency
3 | ------------------------------------------------------------------------------------------
4 | 1. Describe synchronization in respect to multi-threading. What is synchronization.
5 |
6 | Several threads access common data. In order to keep the data in consistent state the access to it has to be synchronized (i.e. some ordering of data access has to be imposed).
7 |
8 | 2. Explain different ways of using thread?
9 |
10 | a) Create a long-running computation in a separate thread so the user interface (or whatever other part of the application) is not blocked.
11 | b) separate out I/O operations which potentially can take a lot of time (e.g. reading from the network) for the same reason
12 | c) process incoming requests in parallel (usually using thread pool of some size)
13 | d) Create thread to do some kind of isolated processing, wait for the processing to finish, kill the thread. Create new threads when needed
14 |
15 | 3. What is the difference between preemptive scheduling and time slicing?
16 |
17 | Not exactly a correct question.
18 |
19 | A scheduler can be preemptive (it's capable to force a process to interrupt its execution and resume it in some time) and non-preemptive (which is unable to interrupt a process and relies on the processes themselves that voluntarily give control to other tasks). Time slicing is a usual technique that is used in a preemptive multitasking system. The scheduler is run every time slice to choose the next process to run (it may happen that it's the same process during few time slices in a row, or it may happen that every time slice a different process is executed )
20 |
21 | To apply these terms to Java world -- replace the "process" with "thread", since the ideas behind scheduling processes in OS are the same as scheduling threads in an application.
22 |
23 | 4. When a thread is created and started, what is its initial state?
24 |
25 | The thread is then in "RUNNABLE" state.
26 |
27 | 5. Thread vs Runnable, run() vs start()
28 |
29 | See below. The main difference between run() and start() is that the latter creates a separate thread while the former executes the code synchronously
30 |
31 | 6. Describe different ways to create a thread.
32 |
33 | a)
34 | class MyRunnable extends SomeOtherClass implements Runnable {
35 | public void run(){
36 | // code that has to run in a thread
37 | }
38 | }
39 |
40 | MyRunnable r = new MyRunnable();
41 | Thread t = new Thread(r);
42 | r.start();
43 |
44 | b)
45 | class MyThread extends Thread {
46 | public void run(){
47 | // code that has to run in a thread
48 | }
49 | }
50 |
51 | Thread t = new MyThred();
52 | t.start();
53 |
54 | c)
55 | class MySomething extends Something {
56 | public void doSomeStuff() {...}
57 | }
58 |
59 | new Thread(new Runnable() {
60 | public void run(){
61 | instanceOfMySomething.doSomeStuff();
62 | }
63 | }).start();
64 |
65 | The main difference between these two approaches is that in case (a) you are able to extend the class you need while still being able to run your code in a separate thread. In case (b) you are already extending from the Thread class which limits your options. In general following one of the good OOP practices (Favor composition over inheritance) option (a) is preferable. Option (c) is also cute since it decouples your class and the fact that its code will be run in a separate thread. In other words you can still call instanceOfMySomething.doSomeStuff() regardless from a new thread or from the same.
66 |
67 | 7. Synchronization of Java blocks and methods
68 |
69 | Methods declared synchronized and statements contained in synchronized blocks. Only one thread is allowed to be executing instructions inside a synchronized block. The main difference between synchronized block and synchronized method is that you can choose which object will be used for synchronization in case of blocks. The methods are always synchronized with "this"
70 |
71 | 8. Explain usage of the couple wait()/notify()
72 |
73 | The mechanism is used to allow one thread to signal another. E.g. Consumer signals that he's waiting for the next object to process, or Producer signals that a new object is ready to be processed.
74 |
75 | wait( ) tells the calling thread to give up the monitor and go to sleep until some other thread enters the same monitor and calls notify( ).
76 | notify( ) wakes up the a thread (a random one?) that called wait( ) on the same object.
77 | notifyAll( ) wakes up all the threads that called wait( ) on the same object.
78 |
79 |
80 | 9. What does Volatile keyword mean?
81 |
82 | The volatile keyword guarantees that reads and from a variable will see the changes made by the last write to this variable (and of course all other writes that happened earlier). Java documentation states that volatile establishes a "happens-before" relationship between a write to a variable and all subsequent reads from it.
83 |
84 | 10. java.util.concurrent.*, what utils do you know?
85 |
86 | Synchronization primitives: Semaphore, CyclicBarrier, CountDownLatch, Lock, ReentrantLock
87 | Threads: Executors, Callable and Future
88 | Data: Synchronized collections (CopyOnWriteArrayList, ConcurrentHashMap, BlockingQueue)
89 |
90 | 11. ThreadLocal, what for are they needed? Does child thread see the value of parent ThreadLocal?
91 |
92 | Values stored in Thread Local are global to the thread, meaning that they can be accessed from anywhere inside that thread. If a thread calls methods from several classes, then all the methods can see the Thread Local variable set by other methods (because they are executing in same thread). The value need not be passed explicitly. It’s like how you use global variables.
93 |
94 | One possible (and common) use is when you have some object that is not thread-safe, but you want to avoid synchronizing access to that object. Instead, give each thread its own instance of the object. ThreadLocals are one sort of global variables (although slightly less evil because they are restricted to one thread), so you should be careful when using them to avoid unwanted side-effects and memory leaks. Design your APIs so that the ThreadLocal values will always be automatically cleared when they are not anymore needed and that incorrect use of the API won't be possible (for example like this).
95 |
96 | No. The child thread doesn't see the value of parent ThreadLocal unless InheritableThreadLocal is used.
97 |
98 | 12. Recommendations to avoid deadlocks.
99 |
100 | a) We may create a class that will register all locks being held by all the threads. Thus before granting a new lock to a thread we may check whether it will not lead to a deadlock and grant the lock only if it doesn't.
101 | b) We may devise a policy of acquiring the locks by the threads that will guarantee a deadlock-free program. A simple example of such policy is: no thread is allowed to have more than one lock at a time.
102 |
103 | 13. What is daemon thread and which method is used to create the daemon thread?
104 |
105 | A daemon thread is a thread, that does not prevent the JVM from exiting when the program finishes but the thread is still running. An example for a daemon thread is the garbage collection. The setDaemon() method can be used to change the Thread daemon properties. Normal thread and daemon threads differ in what happens when they exit. When the JVM halts any remaining daemon threads are abandoned: finally blocks are not executed, stacks are not unwound - JVM just exits. Due to this reason daemon threads should be used sparingly and it is dangerous to use them for tasks that might perform any sort of I/O.
106 |
107 | 14. What method must be implemented by all threads?
108 |
109 | run(); by default (in the Thread class itself) it does nothing and returns
110 |
111 | 15. What is the difference between process and thread?
112 |
113 | From Java documentation: A process has a self-contained execution environment. A process generally has a complete, private set of basic run-time resources; in particular, each process has its own memory space. Most implementations of the Java virtual machine run as a single process
114 |
115 | Threads are sometimes called lightweight processes. Both processes and threads provide an execution environment, but creating a new thread requires fewer resources than creating a new process. Threads exist within a process - every process has at least one. Threads share the process's resources, including memory and open files. This makes for efficient, but potentially problematic, communication.
116 |
117 | 16. What are the states associated in the thread?
118 |
119 |
120 |
121 | 17. When you will synchronize a piece of your code?
122 |
123 | Whenever there will be a need: most probably when there will be concurrent access to some data
124 |
125 | 18. What is deadlock? Example of deadlock.
126 |
127 | Deadlock is a state in which some threads of an application (at least two threads) are mutually blocked (A waits for resource X held by B, while B waits for resource Y held by A). Neither can continue in this case. Note that only part of application can be in a deadlock state while other thread continue their execution.
128 |
129 | public class DeadlockTest {
130 | public static void main(String[] args) {
131 |
132 | String s1 = "S1";
133 | String s2 = "S2";
134 |
135 | Thread t1 = new Thread(new DeadlockCause(s1, s2));
136 | Thread t2 = new Thread(new DeadlockCause(s2, s1));
137 |
138 | t1.start();
139 | t2.start();
140 |
141 | }
142 | }
143 |
144 | class DeadlockCause implements Runnable {
145 |
146 | private final Object firstLock;
147 | private final Object secondLock;
148 |
149 | public DeadlockCause(Object o1, Object o2) {
150 | firstLock = o1;
151 | secondLock = o2;
152 | }
153 |
154 | @Override
155 | public void run() {
156 | synchronized(firstLock){
157 | System.out.println(Thread.currentThread().getName() + " holds the lock on " + firstLock);
158 | try {
159 | Thread.sleep(1000);
160 | } catch (InterruptedException ex) {
161 | Logger.getLogger(DeadlockCause.class.getName()).log(Level.SEVERE, null, ex);
162 | }
163 |
164 | System.out.println(Thread.currentThread().getName() + " tries to get the lock on " + secondLock);
165 | synchronized(secondLock){
166 | System.out.println(Thread.currentThread().getName() + " holds the lock on " + secondLock);
167 | }
168 | }
169 | }
170 | }
171 |
172 | 19. Are there any global variables in Java, which can be accessed by other part of your program?
173 |
174 | No, there are no global variables in Java.
175 |
176 | 20. What are Callable and FutureTask interfaces?
177 |
178 | Motivation to create: with Thread and Runnable you cannot return a value as the result of executing the task. Additionally you have to process all the exception inside the run() method because its declaration is public void run() and doesn't allow exceptions to be thrown.
179 | The Callable has the method public T call() throws Exception. When an ExecutorService gets submitted a Callable it returns a Future. The get() method on this Future instance has to be called in order to get the result
180 |
181 | Example:
182 |
183 | ExecutorService executor = Executors.newFixedThreadPool();
184 | Future future = executor.submit(new Callable(){
185 | public Integer call() throws Exception {
186 | Integer result = 0;
187 | // do some stuff here
188 | return result;
189 | }
190 | });
191 |
192 | executor.shutdown(); // stop accepting new tasks
193 |
194 | try {
195 | System.out.println("The result is: " + future.get());
196 | } catch (InterruptedException ex) {
197 | ...
198 | }
199 |
200 |
201 | 21. What is Executors framework?
202 |
203 | See
204 | http://docs.oracle.com/javase/tutorial/essential/concurrency/exinter.html
205 |
206 | 22. What is AtomicInteger
207 |
208 | AtomicInteger is a class from java.util.concurrent package that provides thread-safe implementation of an Integer.
209 | More information on AtomicXXX can be found at http://docs.oracle.com/javase/6/docs/api/java/util/concurrent/atomic/package-summary.html
210 |
211 |
212 | ------------------------------------------------------------------------------------------
213 | Advanced Concurrency Questions
214 | ------------------------------------------------------------------------------------------
215 |
216 | The following questions have been taken from http://www.rsdn.ru/forum/java/3622844.all and translated into English
217 | Good set of answers can be found here http://swein2.blogspot.ch/2011/10/concurrency.html
218 |
219 | ------------------------------------------------------------------------------------------
220 |
221 | Differences in JMM before Java 5 and after Java 5?
222 | What is the difference between Runnable and Callable?
223 | What is the difference between java.util.concurrent.Atomic*.compareAndSwap() and java.util.concurrent.Atomic*.weakCompareAndSwap()?
224 | What is the difference between Collections.synchronizedMap(new HashMap()) and ConcurrentHashMap?
225 | What is the difference between Thread.isInterrupted() and Thread.interrupted()?
226 | What is the difference between CountDownLatch and CyclicBarrier?
227 | What is the difference between ReenetrantLock and synchronized{}
228 | Can you list all the reasons when InterruptedException can be thrown?
229 | In SynchronousQueue what is unique for BlockingQueue?
230 | In the String class all the fields are final. Could we remove the final keyword, since the class doesn't have any setters and thus the fields cannot be changed.
231 | What happens when you call Thread.interrupt()?
232 | What are advantages of ScheduledThreadPool over java.util.Timer?
233 | Thread.getState() returns an instance of Thread.State. What are the possible values?
234 | ReentrantLock created with a true flag (fair) one of the methods to get the lock is not fair. Which one? When to use or not use it?
235 | Which of the following calls creates a happens-before relationship? Thread.sleep(), Thread.join(), Thread.yield(), Thread.start(), Thread.run(), Thread.isAlive(), Thread.getState()?
236 | Some of the following methods are deprecated, some have never been implemented. Which of them fall into which category? Thread.interrupt(), Thread.stop(), Thread.yield(), Thread.suspend(), Thread.resume(), Thread.join(), Thread.start(), Thread.run(), Thread.sleep()
237 | What are ordering, visibility, atomicity, happens-before, mutual exclusion? Which of the listed properties are retained when using volatile, AtomicInteger and synchronized{}? How?
238 | What do you know about asynchronous method calls? Do they exist in Java? If yes, how they are implemented? If no, how would you implement them?
239 | What is rendez-vous? Which Java classes can help?
240 | What is a "green thread"? Are they used in Java (in HotSpon JVM.6)?
241 | What is cooperative multitasking? Is it used in Java? If not then which type of multitasking is used in Java? What are the advantages.
242 | What is false sharing? Could it happen in Java? If yes, how could you fight it? If no, how the JVM developers have overcome it?
243 |
244 | Explain safe publication.
245 | Explain recursive parallelism.
246 | Explain iterative parallelism.
247 | Tell something about Reactor/Proactor patterns.
248 | What does reentrant property mean?
249 | List the ways to fight priority inversion. Name the types of systems where they are extremely dangerous.
250 | Name the ways to a) avoid b) overcome a deadlock (imagine you're writing a RDBMS kernel)
251 |
252 | What is monitor?
253 | What is private mutex?
254 | What is priority inheritance?
255 | What is back-off protocol (exponential back-off)?
256 | What is task-stealing?
257 | What is spin lock?
258 | What is sequential consistency?
259 | What is ABA problem?
260 | What is "test and set"?
261 | What is "test and set and set"?
262 | What is "sense reversing barrier"?
263 | What is pipeline?
264 | What is poison message?
265 | What is mutual exclusion? Examples.
266 | What is condition waiting? Examples.
267 |
268 | Implement a simple nonblocking stack (only push() and pop())
269 | Implement a simple copy-on-write ArrayList (void add(int index, T item), T get(int index), void remove(int index), int size())
270 | Implement a simple buffer for multiple producers / multiple consumers using synchronized{}
271 | Implement a simple buffer for multiple producers / multiple consumers using ReentrantLock
272 |
273 |
274 |
275 |
276 |
--------------------------------------------------------------------------------
/Java Core/Java Exceptions.txt:
--------------------------------------------------------------------------------
1 | ------------------------------------------------------------------------------------------
2 | Exceptions
3 | ------------------------------------------------------------------------------------------
4 |
5 | 1. What are Checked and UnChecked Exception?
6 |
7 | Checked -- exceptions that the program has to handle with and to be able to succesfully recover from.
8 | Unchecked (Runtime) -- usually signal of a programmatic error. Potentially can happen anywhere
9 | Error -- something really bad happened to the JVM or system. Usually cannot be recovered from.
10 |
11 | 2. What are runtime exceptions?
12 |
13 | See above.
14 |
15 | 3. What is the difference between error and an exception?
16 |
17 | See above.
18 |
19 | 4. How to create custom exceptions?
20 |
21 | Extend from Exception class or from RuntimeException class.
22 |
23 | 5. If I want an object of my class to be thrown as an exception object, what should I do?
24 |
25 | Extend from Exception class (or any of its subclasses)
26 |
27 | 6. If my class already extends from some other class what should I do if I want an instance of my class to be thrown as an exception object?
28 |
29 | Nothing. There is no Exception interface.
30 |
31 | 7. How does an exception permeate through the code?
32 |
33 | It's either caught or it is going to be passed to the next level in call stack.
34 | If it's caught it can be rethrown as another Exception which has to be processed in a higher level.
35 |
36 | 8. What are the different ways to handle exceptions?
37 |
38 | Declare that the methods throws an exception or catch it.
39 |
40 | 9. What is the basic difference between the 2 approaches to exception handling...1> try catch block and 2> specifying the candidate exceptions in the throws clause?
41 |
42 | The main difference is in who is responsibile for handling the exception.
43 |
44 | 10. When should you use which approach?
45 |
46 | As I understand one should handle the exception if he/she has all the knowledge and resources to do so. And the exception has to be handled as soon as this knowledge is aquired. However if you are writing a library you may consider declaring the exceptions that are thrown and force the user of the library to decide how to react to a specific situation. The downside of this approach is that declared exceptions become the part of the API which has to be frozen after being published.
47 |
48 | 11. Is it necessary that each try block must be followed by a catch block?
49 |
50 | No. It can be followed by either catch block or finally block or both.
51 |
52 | 12. If I write return at the end of the try block, will the finally block still execute?
53 |
54 | Yes it will.
55 |
56 | 13. If I write System.exit (0); at the end of the try block, will the finally block still execute?
57 |
58 | No it won't. It also won't execute if the thread where the exception is thrown is terminated.
59 |
60 | 14. How does a try statement determine which catch clause should be used to handle an exception?
61 |
62 | The first that has a matching exception type declared.
63 |
64 | 15. What is the catch or declare rule for method declarations?
65 |
66 | blah-blah-blah. If you are using a checked exception you either have to catch it or declare that it could be thrown by a method.
67 |
68 | 16. Pros and cons of using exceptions vs. returning "error value"
69 |
70 | Exceptions provide clearer understanding and better code
71 | Exceptions can be grouped together to be handled
72 | Exceptions can be propagated up in the call stack to be handled where they are supposed to be handled.
73 | Exception handling could be slow.
74 | In some sense Exceptions are unignorable error codes.
75 |
76 | For example, exceptions are intrusive (eg if they're not handled the program dies). If you have an error that can be safely ignored, being forced to catch and handle can be painful. However, they're definitely appropriate if the result of quietly ignoring an error is something that will bite you later.
77 |
78 | 17. Cases when the finally block isn't executed
79 |
80 | System.exit() in try or catch block.
81 | Error in one of the blocks (e.g. OutOfMemoryError)
82 | Thread is terminated, while the whole application still continues.
83 |
84 | 18. What is exception handling mechanism
85 |
86 | Blah-blah-blah.
87 |
88 | 19. Bundled exceptions
89 |
90 | IllegalArgumentException
91 | ConcurrentModificationException
92 | IllegalStateException
93 | UnsupportedOperationException
94 | ArithmeticException
95 | NullPointerException
96 | ArrayIndexOutOfBoundsException
97 | IOException
98 |
99 | 20. How to avoid catch block?
100 |
101 | Declare that method throws the exception. You can still use try/finally.
--------------------------------------------------------------------------------
/Java Core/Java GUI.txt:
--------------------------------------------------------------------------------
1 | ------------------------------------------------------------------------------------------
2 | Swing
3 | ------------------------------------------------------------------------------------------
4 |
5 |
6 |
7 | ------------------------------------------------------------------------------------------
8 | AWT
9 | ------------------------------------------------------------------------------------------
10 |
11 | 1. What is an event and what are the models available for event handling?
12 | 2. What are the advantages of the model over the event-inheritance model?
13 | 3. What is source and listener?
14 | 4. What is adapter class?
15 | 5. What is meant by controls and what are different types of controls in AWT?
16 | 6. What is the difference between choice and list?
17 | 7. What is the difference between scrollbar and scrollpane?
18 | 8. What is a layout manager and what are different types of layout managers available in java AWT?
19 | 9. How are the elements of different layouts organized?-
20 | 10. Which containers use a Border layout as their default layout?
21 | 11. Which containers use a Flow layout as their default layout?
22 | 12. Difference between Swing and Awt?
--------------------------------------------------------------------------------
/Java Core/Java Generics.txt:
--------------------------------------------------------------------------------
1 | ------------------------------------------------------------------------------------------
2 | Generics
3 | ------------------------------------------------------------------------------------------
4 |
5 | Very good collection of Q&A about Java Generics can be found
6 | http://www.angelikalanger.com/GenericsFAQ/JavaGenericsFAQ.html
7 |
8 |
9 | Questions
10 | -------------------------------
11 |
12 | 1. What is Generics in Java ? What are advantages of using Generics?
13 |
14 | They allow "a type or method to operate on objects of various types while providing compile-time type safety." A common use of this feature is when using a Java Collection that can hold objects of any type, to specify the specific type of object stored in it.
15 |
16 | A class is generic if it declares one or more type variables.
17 |
18 | 2. How Generics works in Java ? What is type erasure ?
19 |
20 | The type safety is ensured during the compile time. In run time the information about type arguments is erased. The type arguments are replaced by their narrowest superclass. For unbounded parameters -- Object. For bounded -- the declared bound.
21 |
22 | 3. What is Bounded and Unbounded wildcards in Generics ?
23 |
24 | The wildcard type is signified by "?" in Java. Classes parametrized by wildcard are usually read as "class of some type", e.g. List> is read List of some type.
25 |
26 | A wildcard parameterized type is an instantiation of a generic type where at least one type argument is a wildcard. Examples of wildcard parameterized types are Collection>, List extends Number>, Comparator super String> and Pair.A wildcard parameterized type denotes a family of types comprising concrete instantiations of a generic type. The kind of the wildcard being used determines which concrete parameterized types belong to the family. For instance, the wildcard parameterized type Collection> denotes the family of all instantiations of the Collection interface regardless of the type argument. The wildcard parameterized type List extends Number> denotes the family of all list types where the element type is a subtype of Number. The wildcard parameterized type Comparator super String> is the family of all instantiations of the Comparator interface for type argument types that are supertypes of String.
27 |
28 | A wildcard parameterized type is not a concrete type that could appear in a new expression. A wildcard parameterized type is similar to an interface type in the sense that reference variables of a wildcard parameterized type can be declared, but no objects of the wildcard parameterized type can be created. The reference variables of a wildcard parameterized type can refer to an object that is of a type that belongs to the family of types that the wildcard parameterized type denotes.
29 |
30 | 4. What is wildcard prameter
31 |
32 | In generic code, the question mark (?), called the wildcard, represents an unknown type. The wildcard can be used in a variety of situations: as the type of a parameter, field, or local variable; sometimes as a return type (though it is better programming practice to be more specific). The wildcard is never used as a type argument for a generic method invocation, a generic class instance creation, or a supertype.
33 |
34 | 5. What is difference between List extends T> and List super T> ?
35 |
36 | The first list may contain elements of type T or any of its subtypes.
37 | The second list may contain elements of type T or any of its supertypes.
38 |
39 | For any type X such that X is a subtype of T or T itself
40 | List is a subtype of List extends T>
41 |
42 | For any type Y such that Y is a supertype of T or T itself
43 | List is a subtype of List super T>
44 |
45 | List> is supertype of any parametrized list.
46 |
47 | 6. How to write a generic method which accepts generic argument and return Generic Type?
48 |
49 | Generic method in a generic class
50 |
51 | public class SomeClass{
52 | private T value;
53 |
54 | // T is already declared
55 | // since it's type parameter of the class
56 | public T doSomething(){...}
57 |
58 | // U has to be declared since it's not type parameter of the class
59 | public List createSingleElementList(U arg){
60 | List result = new ArrayList();
61 | result.add(arg);
62 | return result;
63 | }
64 | }
65 |
66 | Static generic method
67 |
68 | public static T doSomething(T value){...}
69 |
70 | 7. How to write parametrized class in Java using Generics ?
71 |
72 | class SomeClass extends SomeSuperClass implements SomeInterface
73 | class SomeClass>
74 | class SomeClass
75 |
76 | 8. Can you pass List to a method which accepts List