Sei sulla pagina 1di 10

ASSIGNMENT 1

Why does Java strictly specify the range and behavior of its primitive types?
What is Javas character type, and how does it differ from the character type used by some other
programming languages?
A boolean value can have any value you like because any non-zero value is true. True or False?
Explain the difference between the prefix and postfix forms of the increment operator.
Show how a short-circuit AND can be used to prevent a divide-by-zero error.
In an expression, what type are byte and short promoted to?
In general, when is a cast needed?
Write a program that finds all of the prime numbers between 2 and 100.
Does the use of redundant parentheses affect program performance?
Does a block define a scope?
Write for statement for a loop that counts from 1000 to 0 by 2.
Explain what break does. Be sure to explain both of its forms.
The iteration expression in a for loop need not always alter the loop control variable by a fixed
amount. Instead, the loop control variable can change in any arbitrary way. Using this concept,
write a program that uses a for loop to generate and display the progression 1, 2, 4, 8, 16, 32,
and so on.
What is an infinite loop?
When using break with a label, must the label be on a block that contains the break?
What is the difference between a class and an object?
How is a class defined?
Show how a method called myMeth( ) is declared if it has a return type of double and has
two int parameters called a and b.
How must a method return if it returns a value?
What name does a constructor have?
What does new do?
What is garbage collection, and how does it work? What is finalize( )?
What is this?
Can a constructor have one or more parameters?
If a method returns no value, what must its return type be?
Show two ways to declare a one-dimensional array of 12 doubles.
Show how to initialize a one-dimensional array of integers to the values 1 through 5.
Write a program that uses an array to find the average of 10 double values. Use any 10 values
you like.
What is the difference between the String methods indexOf( ) and lastIndexOf( )?
Since all strings are objects of type String, show how you can call
the length( ) and charAt( ) methods on this string literal: "I like Java".
Can the bitwise operators be applied to the double type?
Is it an error to overrun the end of an array? Is it an error to index an array with a negative value?
What is the unsigned right-shift operator?
Can a String control a switch statement?
An access modifier must __________ a members declaration.
The complement of a queue is a stack. It uses first-in, last-out accessing and is often likened to a
stack of plates. The first plate put on the table is the last plate used. Create a stack class
called Stack that can hold characters. Call the methods that access the stack push( ) and pop( ).
Allow the user to specify the size of the stack when it is created. Keep all other members of
the Stack class private. (Hint: You can use the Queue class as a model; just change the way the
data is accessed.)

write a method called swap( ) that exchanges the contents of the objects referred to by
two Test object references.
Write a recursive method that displays the contents of a string backwards.
If all objects of a class need to share the same variable, how must you declare that variable?
Why might you need to use a static block?
What is an inner class?
To make a member accessible by only other members of its class, what access modifier must be
used?
The name of a method plus its parameter list constitutes the methods _______________.
An int argument is passed to a method by using call-by-_______________.
Create a varargs method called sum( ) that sums the int values passed to it. Have it return the
result. Demonstrate its use
Can a varargs method be overloaded?
Show an example of an overloaded varargs method that is ambiguous.

ASSIGNMENT 2

1.

Write a program to swap two values in java using object references

http://www.javaworld.com/article/2077424/learn-java/does-java-pass-by-reference-or-pass-byvalue.html

ASSIGNMENT 3: Inheritance

1. Does a superclass have access to the members of a subclass? Does a subclass have access to the
members of a superclass?
2. Create a subclass of TwoDShape called Circle. Include an area( ) method that computes the area of the
circle and a constructor that uses super to initialize the TwoDShape portion.
3. How do you prevent a subclass from having access to a member of a superclass?
4. Describe the purpose and use of the two versions of super.
5. A superclass reference can refer to a subclass object. Explain why this is important as it relates to method
overriding.
6. What is an abstract class?
7. How do you prevent a method from being overridden? How do you prevent a class from being inherited?

8. Explain how inheritance, method overriding, and abstract classes are used to support polymorphism.
9. What class is a superclass of every other class?
10. A class that contains at least one abstract method must, itself, be declared abstract. True or False?

11. What keyword is used to create a named constant?

ASSIGNMENT 3: Packages and Interfaces

1. What is a namespace? Why is it important that Java allows you to partition the namespace?
2. Packages are stored in ______________.
3. Explain the difference between protected and default access.
4. Explain the two ways that the members of a package can be used by other packages.
5. One interface, multiple methods is a key tenet of Java. What feature best exemplifies it?
6. How many classes can implement an interface? How many interfaces can a class implement?
7. Can interfaces be extended?
8. Variables declared in an interface are implicitly static and final. Can they be shared with other parts of a
program?
9. A package is, in essence, a container for classes. True or False?
10. What standard Java package is automatically imported into a program?
11. What keyword is used to declare a default interface method?
12. Beginning with JDK 8, is it possible to define a static method in an interface?
13. How is a static method in an interface called?

ASSIGNMENT 3: Exception Handling


1.
2.
3.
4.
5.
6.
7.
8.
9.

What class is at the top of the exception hierarchy?


What happens if an exception is not caught?
Can an inner catch rethrow an exception to an outer catch?
The finally block is the last bit of code executed before your program ends. True or
False? Explain your answer.
What type of exceptions must be explicitly declared in a throws clause of a method
What are the three ways that an exception can be generated?
What are the two direct subclasses of Throwable?
What is the multi-catch feature?
Should your code typically catch exceptions of type Error?

ASSIGNMENT 4
1. Exception Handling: Write a program to demonstrate the use of try, catch, finally throw and throws
keywords and demonstrate the following points in the program.
a) Multiple catch blocks. b) try-catch-finally combination. c) try-finally combination. d) Exception propagation
among many methods. e) Use of getMessage(), printStackTrace() function of Throwable class. f) Nested try
blocks
2. Write a program to throw a checked exception explicitly using 'throw' keyword and a) Handle the exception
in same method. b) use throws clause and handle the exception in some other method (calling method) c)
Don't either handle or use the throws clause.
3. Repeat program 2 with unchecked Exception and demonstrate the difference in both program.
4. Introduction to Classes and Members: Create a new Class Customer. Define a static variable custCount.
This contains total count of customers Create 2 instances of Customer object Increment the custCount static
variable and print its value after every increment Access custCount using class name as well as object name
5. Constructors: Define a private constructor for Employee class Define a protected constructor for Employee
class Invoke both private and protected constructors from the main method. Does the program execute? Invoke
both private and protected constructors from the subclass say ContractEmp. Does the program execute?
Remove the public constructor for Employee class. How will another class create instance of Employee class?
6. Inheritance: Create a subclass Contractor for base class Employee.Define some variables for Employee
class. Define a constructor for Contractor. Can you initialize all variables defined in the base class? Create
instance of subclass Contractor. Are base class constructors accessible? Invoke Contractor's constructor.
Which all constructors are getting invoked? Define a variable in Contractor matching its definition in the base
class Employee. Is that allowed?
7. Polymorphism: Create base class Customer and subclasses SilverCustomer and GoldCustomer Define
discount() method in Customer class whcih returns 20% discount Overload discount method in the subclasses
and return different discount value Define base class variable as "Customer cust" Assign different objects of
Customer, SilverCustomer and GoldCustomer to variable cust one after other and invoke discount method
each time. What is the discount % returned each time?
8. Interfaces: Create a new interface to develop a simple Calculator Define two methods sum and divide in the
interface. Can you implement the methods inside the interface? Create a new class which implements above
interface. Do you need to implement both the methods here? Define a variable inside calculator interface? Can
it be invoked from calculator implementation? Now define one more interface ScientificCalculator and add
couple of methods Can you implementation class implement this new interface as well? Try it.
9. Collections: Define the following collections with some values a. ArrayList b. HashSet c. HashMap d.
Hashtable Iterate through all elements of collection using Enumeration and Iterator Interface and remove an
element of each collection using these Interface.
10. Write a program to demonstrate the use of equals method of Object class and compare its functionality with
( = = ) operator.
11. Write a program to check if a string is a palindrome
12. Write a program to multiply a 2x2 matrix using arrays

Some Notes:

Understand Difference between stack space, heap space and perm space.
The heap stores all of the objects created by your Java program. The heap's content is monitored by the
garbage collector, which frees memory from the heap when you stop using an object.
Java "Heap" is a continuous memory region where all Objects data will be stored (by data, we mean
instance of class, primitive and references). It's a big part of the process heap. It can be configured using the
following parameters:
-Xmx : max heap size (ex: -Xmx1024)
-Xms : min heap size. Having -Xms = 1.8GB (32bit) can be bad, because you don't let memory for
anything else.
-Xmn : the size of the heap for the young generation
Young generation represents all the objects which have a short life of time. Young generation objects are in a
specific location into the heap, where the garbage collector will pass often. All new objects are created into the
young generation region. When an object survive is still "alive" after more than 2-3 garbage collector cleaning,
then it will be swap has an "old generation" : they are "survivor" .
Stack is a memory place where the methods and the local variables are stored

The permanent generation is special because it holds meta-data describing user classes (classes that are not
part of the Java language). Examples of such meta-data are objects describing classes and methods and they
are stored in the Permanent Generation. Applications with large code-base can quickly fill up this segment of
the heap which will cause java.lang.OutOfMemoryError: PermGen does not bother how high your -Xmx and
how much memory you have on the machine.

Understand Differences between Class Not found exception and no class found exception.

ClassNotFoundException is a checked Exception, It is thrown when that required class is not present in the
location where classloader is looking. When an application tries to load in a class through its string name
using: -The forName() method in class Class. -The findSystemClass method() in class ClassLoader. -The
loadClass() method in class ClassLoader. but no definition for the class with the specified name could be
found.
This exception can be created using following program-

import java.net.URL;
import java.net.URLClassLoader;
public class ClassNotFoundExceptionTest {
public static void main(String args[]) {
try {
URLClassLoader loader = new URLClassLoader(new URL[] { new URL(
"file://C:/CL/ClassNotFoundException/")});
loader.loadClass("DoesNotExist");
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (MalformedURLException e) {
e.printStackTrace();
}
}

To avoid this error, User should check the following - - Make sure that
Class is available in the logical
class path of the class loader associated with the class.
- Make sure that
Class Loader API is used
properly .ie whether a wrong class Loader is engaged in Class.forname(). - Make sure that dependent class
of the class being loaded is visible to the class loader.

NoClassDefFoundError is an error .Its thrown to indicate that ClassLoader instance is trying to load in the
definition of a class and no definition of the class is found. The searched-for class definition existed when the
currently executing class was compiled, but the definition can no longer be found.
This error can be recreated using following test program

public class NoClassDefFoundErrorTest {

public static void main(String[] args) {


A a = new A();
}
}
public class A extends B { }
public class B { }
//Once you've compiled the above code remove the classfile for B. When //the code is executed, the following
error occurs
//Exception in thread "main" java.lang.NoClassDefFoundError: B

Possible reasons of the error- -

Bad format of the class -

The version number of a class not matching

This can happen in the distribution or production of JAR files, where not all
the required class files were included.

User should check whether a Class is not available on the classpath(not missing in the jar file). This problem
can occur also when Class cannot load. There are various reasons the class could not be loaded. Possible
reasons include the following: - Failure to load the dependent class - The dependent class has a bad
format. - The version number of the class is incorrect.
The difference between the two is that one is an Error and the other is an Exception.NoClassDefFoundError is
an Error and it arises from fact the Java Virtual Machine having problems finding a class it expected to find. A
program that was expected to work at compile-time can't run because of class files not being found, or is not
the same as was produced or encountered at compile-time. This is a critical error, as the program cannot be
initiated by the JVM.

On the other hand, the ClassNotFoundException is an Exception, which is expected, and recoverable.

ASSIGNMENT 5
Suppose you have an array that has duplicates. Write a program to remove the duplicates from the
array

Suppose you have an array that has duplicates. Find out how many times the elements are repeated
Input:
String Array[] = {"mango","apple","pineapple","mango","apple"}
Output:
mango 2
apple 2
pineapple 1
Suppose there is an array that has elements 1 to 100. Out of this, we are going to insert one more
number that is in between 1-100, add 58 at position 101. Now find out what is the duplicate element
Input:
int[] numbers = new int[101]
a[0]=0;
a[1]=1;
a[2]=2;
..
a[55] = 55;

A[99]=99;
a[100]=55;

Output:
55
Suppose there is an array that has elements 1 to 100. Some of the elements are duplicated. Find out
how many elements are duplicated and list the elements and count.

Write a program to check if a string is a palindrome or not USING RECURSION, lets say the String is
String isPalindrome = MADAM;

ASSIGNMENT 6

Write a Java program that arranges a list of words into separate lists of
anagrams. A text file which will be the input to your program and contains a
list of words to be sorted into anagrams. It will be read by the program. The
number of words in the input is arbitrary but the last word will be followed by a
blank line. The program should print to the standard output the lists of
anagrams in the following way: 1. All the words that are anagrams of each
other are displayed all on one line; words with no anagrams will be displayed
alone.2. The words on each line should be in alphabetical order.3. Lines of
words are sorted alphabetically according to the first word of a line.4. Each
word on a line should be separated by a space but otherwise there should be
no spaces.For example, this input
file car dog bed stop god pots arc tops Should yield the output file arc
car bed dog god pots stop tops

ASSIGNMENT 7
Write a program to simulate producer consumer pattern using wait and notify

ASSIGNMENT 8
1. Create a class for which only one instance can exist in the entire application, so that all application
users interact with the same instance of that class (Singleton Design Pattern)

2. Youve got a utility class that implements an interface, and many different classes within the utility
library implement that interface. Suppose that you want to add a new method to the utility class and
make it available for use for other classes via its interface. However, if you change the interface, it will
break existing classes that already implement that interface. (Hint: Add the new method, along with its
implementation, to the utility class interface as a default method.)

1) how to remove duplicates in an array.


2) count the frequency of duplicates in an array.
3) what is meant by Asynchronous tasking.
4) given braces like ( [ { in an expression and we need to find the highest rank using prefix method.
5) given a 4*4 character array. we need to find all the possible words that can be formed by tranversing either horizontal or
vertical or diagonal way.
6) features of Java 8.
7) write a simple program to illustrate fail fast and fail safe iterators.
8) explain all the features of Object oriented programming.

9) The

sentence
"A quick brown fox jumps over the lazy dog" contains every single letter
in the alphabet. Such sentences are called pangrams. You are to write
a method getMissingLetters, which takes as input a string containing a
sentence and returns all the letters not present at all in the
sentence (i.e., the letters that prevent it from being a pangram). You
should ignore the case of the letters in sentence, and your return
should be all lower case letters, in alphabetical order. You should
also ignore all non-alphabet characters as well as all non-US-ASCII
characters.
Imagine that the method you write will be called many thousands of
times in rapid succession on strings with length ranging from 0 to 50.
Accordingly, you should try to write code that runs as quickly as
possible. Also, imagine the case when the input string is quite large
(e.g., tens of megabytes).

Potrebbero piacerti anche