Department of Computer Applications Iii Semester Mc5304-Programming With Java
Department of Computer Applications Iii Semester Mc5304-Programming With Java
Department of Computer Applications Iii Semester Mc5304-Programming With Java
UNIT I
JAVA FUNDAMENTALS
7. Define API.
Java environment includes a large number of development tools and hundreds of classes
and methods. The development tools are part of the system known as Java Development
Kit (JDK) and the classes and methods are parts of the Java Standard Library (JSL), also
known as the Application Programming Interface (API).
Operator Result
+ Addition
- Subtraction (also unary minus)
* Multiplication
/ Division
% Modulus
++ Increment
+= Addition assignment
-= Subtraction assignment
*= Multiplication assignment
/= Division assignment
%= Modulus assignment
-- Decrement
.
16. Define Bitwise Operators with example
Bitwise operators is used to control values of primitive data-types such as long, integer,
short and byte. These operators do changes to the variables by doing some action and
manipulation on bits level. There are four defined bitwise operators in java which are :
AND operator, OR operator, XOR operator and complement operator. The first three
operators are binary which means that they need two operands while the last one is unary
operator which means it needs only one operand. Next will explain the usage of each
operator by example.
public class Test {
public static void main(String args[]) {
int a = 60; /* 60 = 0011 1100 */
int b = 13; /* 13 = 0000 1101 */
int c = 0;
c = a & b; /* 12 = 0000 1100 */
System.out.println("a & b = " + c );
c = a | b; /* 61 = 0011 1101 */
System.out.println("a | b = " + c );
c = a ^ b; /* 49 = 0011 0001 */
System.out.println("a ^ b = " + c );
c = ~a; /*-61 = 1100 0011 */
System.out.println("~a = " + c );
c = a << 2; /* 240 = 1111 0000 */
System.out.println("a << 2 = " + c );
c = a >> 2; /* 15 = 1111 */
System.out.println("a >> 2 = " + c );
c = a >>> 2; /* 15 = 0000 1111 */
System.out.println("a >>> 2 = " + c );
}
}
17. Define logical operator
A logical operator (sometimes called a “Boolean operator”) in Java programming is an
operator that returns a Boolean result that’s based on the Boolean result of one or two
other expressions.
Sometimes, expressions that use logical operators are called “compound expressions”
because the effect of the logical operators is to let you combine two or more condition
tests into a single expression.
The java instanceof operator is used to test whether the object is an instance of the
specified type (class or subclass or interface).The instanceof in java is also known as type
comparison operator because it compares the instance with type. It returns either true or
false. If we apply the instanceof operator with any variable that has null value, it returns
false.
Example:
class Simple1{
public static void main(String args[]){
Simple1 s=new Simple1();
System.out.println(s instanceof Simple1);//true
}
}
21. Define and list CONTROL STRUCTURE
A control structure is a block of programming that analyzes variables and chooses a
direction in which to go based on given parameters. The term flow control details the
direction the program takes (which way program control "flows")
In Java, control statements can be divided into the following three categories:
Selection Statements
Iteration Statements
Jump Statements
In if-else statements, if the specified condition in the if statement is false, then the
statement after the else keyword (that can be a block) will execute.
import java.util.Scanner;
public class IfElseDemo
{
public static void main( String[] args )
MC5304-programming with java 5119/PEC/MCA
8
{
int age;
Scanner inputDevice = new Scanner( System.in );
System.out.print( "Please enter Age: " );
age = inputDevice.nextInt();
if ( age >= 18 )
System.out.println( "above 18 " );
else
System.out.println( "below 18" );
}
}
if(condition)
statements;
else if (condition)
statements;
else if(condition)
statement;
else
statements;
Whenever the condition is true, the associated statement will be executed and the
remaining conditions will be bypassed. If none of the conditions are true then the else
block will execute.
import java.util.Scanner;
public class IfElseIfDemo
{
public static void main( String[] args )
{
int age;
Scanner inputDevice = new Scanner( System.in );
System.out.print( "Please enter Age: " );
age = inputDevice.nextInt();
if ( age >= 18 && age <=35 )
System.out.println( "between 18-35 " );
else if(age >35 && age <=60)
System.out.println("between 36-60");
else
System.out.println( "not matched" );
}
}
Syntax of switch-case:
switch(expression){
case 1 :
action1 statement;
break;
case 2:
action2 statement;
break;
.
.
.
case N:
actionN statement;
break;
default:
default statement;
}
Repeating the same code fragment several times until a specified condition is satisfied is called
iteration. Iteration statements execute the same set of instructions until a termination condition is
met.
It continually executes a statement (that is usually be a block) while a condition is true. The
condition must return a boolean value.
while (condition) {
action statements:
}
Where condition: is any boolean expression that returns a true or false value. The loop
continues upto condition returns true value.
Example :
int i = 1;
while(i<=5){
i++;
System.out.println(“value of i is : “+i);
The do-while loops execute certain statements till the specified condition is true. This
loop ensures that the loop body is executed atleast once.
Syntax of do-while loop:
do{
action statements;
}while(condition){
action statements;
}
Example :
int j = 8;
do{
j = j+2;
System.out.println(“value of j is : “ +j);
}while(j>=10 && j<=50){
j = j+5;
System.out.println(“value of j is : “ +j);
}
All loops have some common feature: a counter variable that is initialized before the loop
begins. The for loop provides the feature that, initialized the variable before loop begins,
a condition for counter variable and counter upto which loop lasts.
Example :
for(int i=1;i<=10;i++){
System.out.println(“Value of i is “ +i);
}
break statement
continue statement
return statement
Sometimes the programmer might want to continue a loop, but stop processing the
remainder of the code in its body for a particular iteration. The continue statement can be
used for such a scenario. In while and do-while loops, a continue statement can be used,
as shown in below example.
Example :
class ContinueDemo{
public static void main(String args[]){
for(int count = 1; count <= 10; count++){
System.out.println(“Value of count before : “+count);
if(count%2==0){
continue;
}
System.out.println(“Value of count after : “+count);
}
}
}
Polymorphism
Inheritance
Encapsulation
Abstraction
Classes
Objects
Instance
Method
Message Parsing
Object - Objects have states and behaviors. Example: A dog has states - color,
name, breed as well as behaviors – wagging the tail, barking, eating. An object is an
instance of a class.
Class - A class can be defined as a template/blueprint that describes the
behavior/state that the object of its type support.A class is a group of objects which have
common properties. It is a template or blueprint from which objects are created. It is a
logical entity. It can't be physical.
Instance variables: Instance variables are variables within a class but outside any
method. These variables are initialized when the class is instantiated. Instance variables
can be accessed from inside any method, constructor or blocks of that particular class.
Class variables: Class variables are variables declared within a class, outside any
method, with the static keyword.
Each time a new object is created, at least one constructor will be invoked. The main rule
of constructors is that they should have the same name as the class. A class can have
more than one constructor.
Following is an example of a
constructor:
Instance variables and methods are accessed via created objects. To access an instance
variable, following is the fully qualified path:
class Super {
.....
.....
}
class Sub extends Super {
.....
.....
}
An interface is implicitly abstract. You do not need to use the abstract keyword while
declaring an interface.
Each method in an interface is also implicitly abstract, so the abstract keyword is not
needed.
Methods in an interface are implicitly public.
When a class implements an interface, you can think of the class as signing a contract,
agreeing to perform the specific behaviors of the interface. If a class does not perform all the
behaviors of the interface, the class must declare itself as abstract.
A class uses the implements keyword to implement an interface. The implements keyword
appears in the class declaration following the extends portion of the declaration.
// Filename: Football.java
public interface Football extends Sports {
public void homeTeamScored(int points);
public void visitingTeamScored(int points);
public void endOfQuarter(int quarter);
}
// Filename: Hockey.java
public interface Hockey extends Sports {
public void homeGoalScored();
public void visitingGoalScored();
public void endOfPeriod(int period);
public void overtimePeriod(int ot);
}
Autoboxing is the automatic conversion that the Java compiler makes between the primitive
types and their corresponding object wrapper classes. For example, converting an int to
an Integer, a double to a Double, and so on. If the conversion goes the other way, this is
called unboxing. Here is the simplest example of autoboxing:
Creating an exception object and handing it to the runtime system is called throwing an
exception.
The set of possible "somethings" to handle the exception is the ordered list of methods
that had been called to get to the method where the error occurred. The list of methods is
known as the call stack
The runtime system searches the call stack for a method that contains a block of code that
can handle the exception. This block of code is called an exception handler
There are mainly two types of exceptions: checked and unchecked where error is considered as
unchecked exception. The sun microsystem says there are three types of exceptions:
1. Checked Exception
2. Unchecked Exception
3. Error
1) Checked Exception: A checked exception is an exception that occurs at the compile time,
these are also called as compile time exceptions. These exceptions cannot simply be ignored at
the time of compilation, the programmer should take care of (handle) these exceptions.
UNIT II
COLLECTIONS AND ADVANCE FEATURES
The package java.util contains a number of useful classes and interfaces. Although the name
of the package might imply that these are utility classes, they are really more important than
that. In fact, Java depends directly on several of the classes in this package, and many
programs will find these classes indispensable. The classes and interfaces in java.util include:
Interfaces: These are abstract data types that represent collections. Interfaces allow
collections to be manipulated independently of the details of their representation. In object
oriented languages, interfaces generally form a hierarchy.
Implementations, i.e., Classes: These are the concrete implementations of the collection
interfaces. In essence, they are reusable data structures.
Algorithms: These are the methods that perform useful computations, such as searching and
sorting, on objects that implement collection interfaces. The algorithms are said to be
polymorphic: that is, the same method can be used on many different implementations of the
appropriate collection interface.
The Collection Interface : This enables you to work with groups of objects; it is at the top of
the collections hierarchy.
The List Interface: This extends Collection and an instance of List stores an ordered
collection of elements.
The Set: This extends Collection to handle sets, which must contain unique elements
The SortedMap: This extends Map so that the keys are maintained in ascending order.
The Enumeration: This is legacy interface and defines the methods by which you can
enumerate
obtainoneatatime the elements in a collection of objects. This legacy interface has been
superceded by Iterator.
1. ArrayList
2. LinkedList
3. Vectors
Object[] toArray() Returns an array containing all the elements in the list.
Trims the capacity of this ArrayList instance to be the list’s current
void trimToSize()
size.
void add (int index, Object element) Inserts the element at the specified element in the vector.
19. Define Linked Hashset : Java LinkedHashSet class is a Hash table and Linked list
implementation of the set interface. It contains only unique elements like HashSet. Linked
HashSet also provides all optional set operations and maintains insertion order.
20. TreeSet : TreeSet class implements the Set interface that uses a tree for storage. The
objects of this class are stored in the ascending order. Also, it inherits AbstractSet class and
implements NavigableSet interface. It contains only unique elements like HashSet. In
TreeSet class, access and retrieval time are faster.
21. List some of the methods of Java TreeSet class:
Method Description
boolean addAll(Collection c) Add all the elements in the specified collection to this set.
boolean contains(Object o) Returns true if the set contains the specified element.
boolean isEmpty() Returns true if this set contains no elements.
boolean remove(Object o) Remove the specified element from the set.
void add(Object o) Add the specified element to the set.
void clear() Removes all the elements from the set.
Object clone() Return a shallow copy of this TreeSet instance.
Object first() Return the first element currently in the sorted set.
Object last() Return the last element currently in the sorted set.
int size() Return the number of elements in the set.
22. Define generics
Java Generic methods and generic classes enable programmers to specify, with a single
method declaration, a set of related methods, or with a single class declaration, a set of related
types, respectively.
All generic method declarations have a type parameter section delimited by angle
brackets <and><and> that precedes the method's return type <E>in the next example<E>in the
next example .
Each type parameter section contains one or more type parameters separated by commas.
A type parameter, also known as a type variable, is an identifier that specifies a generic type
name.
The type parameters can be used to declare the return type and act as placeholders for the
types of the arguments passed to the generic method, which are known as actual type arguments.
A generic method's body is declared like that of any other method. Note that type
parameters can represent only reference types, not primitive types like int, double and char like
int, double and char .
Collections class provides static methods for sorting the elements of collection. If collection
elements are of Set or Map, we can use TreeSet or TreeMap. But we cannot sort the elements of
List. Collections class provides methods for sorting the elements of List type elements also.
public void sort(List list, Comparator c): is used to sort the elements of List by the given
Comparator.
The manifest of the agent JAR file must contain the attribute Premain-Class. The value of this
attribute is the name of the agent class. The agent class must implement a public static premain
method similar in principle to the main application entry point. After the Java Virtual Machine
(JVM) has initialized, each premain method will be called in the order the agents were specified,
then the real application main method will be called. Each premain method must return in order
for the startup sequence to proceed.
The premain method has one of two possible signatures. The JVM first attempts to invoke the
following method on the agent class:
If the agent class does not implement this method then the JVM will attempt to invoke:
NET/SET/GATE QUESTIONS
A. Private
B. Protected
C. Public
D. Friend
Answer must be C public
because
.2.It is desired to design an object-oriented employee record system for a company. Each
employee has a name, unique id and salary. Employees belong to different categories and
their salary is determined by their category. The functions to get Name, getld and compute
salary are required. Given the class hierarchy below, possible locations for these functions
are: (GATE CS 2004)
i. getld is implemented in the superclass
ii. getld is implemented in the subclass
iii. getName is an abstract function in the superclass
iv. getName is implemented in the superclass
v. getName is implemented in the subclass
vi. getSalary is an abstract function in the superclass
vii. getSalary is implemented in the superclass
viii. getSalary is implemented in the subclass
Answer: (B)
4.
class Test {
public static void main(String args[]) {
int x = -1;
System.out.println(x>>>29);
System.out.println(x>>>30);
System.out.println(x>>>31);
}
}
(A)
7
3
1
(B)
15
7
3
(C)
0
0
0
(D)
1
1
1
Answer: (A)
5.
class Test {
public static void main(String args[]) {
System.out.println(10 + 20 + "GeeksQuiz");
System.out.println("GeeksQuiz" + 10 + 20);
}
}
(A)
30GeeksQuiz
GeeksQuiz30
(B)
1020GeeksQuiz
GeeksQuiz1020
(C)
30GeeksQuiz
GeeksQuiz1020
(D)
1020GeeksQuiz
GeeksQuiz30
Answer: (C)
Answer: (B)
Explanation: There is no sizeof operator in Java. We generally don’t need size of objects.
Answer: (C)
Explanation: t is just a reference, the object referred by t is not allocated any memory. Unlike
C++, in Java all non-primitive objects must be explicitly allocated and these objects are allocated
on heap. The following is corrected program.
class Test {
int i;
}
class Main {
public static void main(String args[]) {
Test t = new Test();
System.out.println(t.i);
}
out.println("GeeksforGeeks");
}
}
Answer: (C)
Answer: (A)
catch(Exception ex)
{
count++;
throw new Exception();
}
}
catch(Exception ex)
{
count++;
}
}
catch(Exception ex)
{
count++;
}
void display()
{
System.out.println(count);
}
Answer: (B)