Documenti di Didattica
Documenti di Professioni
Documenti di Cultura
Introducing the course 1.) Write a java Program to swap two static numbers without using third
handout. variable.
1
2.) Write a java program to find maximum and minimum number from given
three static numbers using conditional operator.
Introducing
Object
3.) Write a java program to print the prime number in the given range.
oriented
programming
1.) Write a Class Circle with a static member radius and a static method to
calculate area and perimeter of a circle that has a radius of 3.7
2 Introduction to Java- 2.) Write a Class runner with a static member runs 14kms in 45 mins and 30
Writing a class, Static secs and display average speed in miles per hr.(Note that one mile is 1.6
block, variables and kms)
methods 3.) Write a class Student with static members as sno, m1, m2, m3 and a static
method to calculate total and average of the m1, m2, m3.
1.) Suppose you save $100 each month into a saving account the annual
interest rate 5% .Thus ,the monthly interest rate is 0.05/12=0.00417.After
3 the first month the value in the account becomes
Modularization and
access specifiers 100*(1+0.00417) = 100.417
2.) Write a program that reads three edges for a triangle and computes the
perimeter if the input is valid otherwise display the input is invalid. The
input is valid if the sum of every pair of two edges greater than remaining
edge.
3.) Write a program to return TRUE if the year is leap year else return FALSE
using static method.
1.) Modularize sum of n numbers using static variable, static method and
static block and calling a method within the same class.
4 Modularization – 2.) Modularize the following problem to class level .Write a Java Code to
class and package
display the speed of bike if speed is greater than or equal to 60 then
level
indicate as over speed, if speed is in between 40 to 60 th6en indicate
average speed otherwise safe drive.
3.) Modularize the following problem to package level .Write a java code to
take an integer n( hard code) and check whether n is divisible by both 3
and 7or by neither of them or by just one of them.
1 Write a java program to will calculate the circumference, area of the circle
using the getter and setter method
5 Creating objects
and accessing www.w3schools.com
members
through object 2 Write a java program, by defining only the setter method to set the values
of the variable
www.w3schools.com
1. toString():
Create a class named Petrol Purchase to represent information about the petrol
you purchase. The class should have five instance variables-the station’s
location(type String),the type of petrol(type String), the quantity(type int), the
price per liter(double),the percentage discount(double). Provide a get() and
set() method for instance variables. In addition, provide a method named
getPurchase() that calculates the net purchase amount.(ref…How To
Program-Tenth Edition…………PAUL DEITEL)
3. Create a class to print the area of a square and a rectangle. The class has
two methods with the same name but different number of parameters. The
method for printing area of rectangle has two parameters which are length and
breadth respectively while the other method for printing area of square has
one parameter which is side of square.(The Complete reference)
Java End-of-file
9
Handling I/O – Files,
1) In computing, End Of File (commonly abbreviated EOF) is a
GUI
condition in a computer operating system where no more data can be
read from a data source."
The challenge here is to read lines of input until you reach EOF, then
number and print all lines of content.
Hint: Java's Scanner.hasNext () method is helpful for this problem.
Input Format
Read some unknown n lines of input from stdin (System.in) until you
reach EOF; each line of input contains a non-empty String.
Output Format
For each line, print the line number, followed by a single space, and
then the line content received as input.
Sample Input
Hello world
I am a file
Read me until end-of-file.
Sample Output
1 Hello world
2 I am a file
3 Read me until end-of-file.
Reference link:
https://www.hackerrank.com/challenges/java-end-of-
file/problem?h_r=internal-search
3. Develop a JFrame that has text area field which accepts lines of text from
the user and button count words. Now write a java program to return number
of characters and words in the inputted text.
1. Write a program that creates an employee class with empid, name, salary as
its members. Create constructors to give initial values to class members and
Constructors- types and include garbage collectors to destroy the objects created.
10
this keyword
2. Develop a java program to create a Class Vehicle with wheels and color as
it member. Now create parameterized and no parameterized constructors that
assign values to Vehicle class members with appropriate display messages.
Also define corresponding destructors
https://beginnersbook.com/2013/12/java-constructor-chaining-with-
example/
3. Suppose you have a Piggie Bank with an initial amount of $50 and
you have to add some more amount to it. Create a class 'AddAmount'
with a data member named 'amount' with an initial value of $50. Now
make two constructors of this class as follows:
A- without any parameter - no amount will be added to the Piggie Bank
B- having a parameter which is the amount that will be added to Piggie
Bank
Create object of the 'AddAmount' class and display the final amount in
Piggie Bank.
12 Object as argument and 1. Create a class named 'Programming'. While creating an object of the
return value. Call by
value vs Call by class, if nothing is passed to it, then the message "I love programming
reference languages" should be printed. If some String is passed to it, then in
place of "programming languages" the name of that String variable
should be printed.For example, while creating object if we pass "Java",
then "I love Java" should be printed.
2. Create a class 'Student' with three data members which are name,
age and address. The constructor of the class assigns default values
name as "unknown", age as '0' and address as "not available". It has
two members with the same name 'setInfo'. First method has two
parameters for name and age and assigns the same whereas the second
method takes has three parameters which are assigned to name, age
and address respectively. Print the name, age and address of 10
students.
13 https://www.w3schools.com/java/java_inner_classes.asp
Nested and inner
classes
https://www.codechef.com/problems/MRO
1 Protected specifier
2 Protected method
https://www.geeksforgeeks.org/access-modifiers-java/
write a java program which Create two packages p1 and p2. Class A in p1 is
made public, to access it in p2. The method display in class A is protected
and class B is inherited from class A then access the method. protected void
display()
class Sports{
String getName(){
return "Generic Sports";
void getNumberOfTeamMembers(){
Next, we create a Soccer class that inherits from the Sports class. We can
override the getName method and return a different, subclass-specific string:
@Override
String getName(){
Note: When overriding a method, you should precede it with the @Override
annotation. The parameter(s) and return type of an overridden method must
be exactly the same as those of the method inherited from the supertype.
Task
Complete the code in your editor by writing an overridden
getNumberOfTeamMembers method that prints the same statement as the
superclass' getNumberOfTeamMembers method, except that it replaces with
(the number of players on a Soccer team).
Output Format
Generic Sports
Soccer Class
https://www.hackerrank.com/challenges/java-method-overriding-2-
super-keyword/problem
When a method in a subclass overrides a method in superclass, it is still
possible to call the overridden method using super keyword. If you write
super.func() to call the function func(), it will call the method that was
defined in the superclass.
You are given a partially completed code in the editor. Modify the code so
that the code prints the following text:
Hello I am a motorcycle, I am a cycle with an engine.
3) Super keyword
Write an employee class Janitor to accompany the other employees. Janitors
work twice as many hours (80 hours/week), they make $30,000 ($10,000 less
than others), they get half as much vacation (only 5 days), and they have an
additional method named clean that prints "Workin' for the man."
Note: Use the super keyword to interact with the Employee superclass as
appropriate.
REF: https://courses.cs.washington.edu/courses/cse142/12su/labs/lab9-
inheritance.shtml#slide15
4 Bank Interest
https://www.javatpoint.com/method-overriding-in-java
https://www.geeksforgeeks.org/dynamic-method-dispatch-runtime-polymorphism-java/
A Java program to illustrate Dynamic Method
// Dispatch using hierarchical inheritance
Given class are A,B,C ,dispatch
Write the code for dispatch class show Dynamic Method Dispatch.
Class A
{
Void m1()
{
System.out.println("Inside A's m1 method");
}
}
classB extendsA
{
// overriding m1()
Void m1()
{
System.out.println("Inside B's m1 method");
}
}
classC extendsA
{
// overriding m1()
Void m1()
{
System.out.println("Inside C's m1 method");
}
}
// Driver class
Class Dispatch
{
publicstaticvoidmain(String args[])
{
…………
……
Write the code for Dynamic dispatch which access all M1()methods using
super class.
1 Super Keyword
21 Super class variable Demonstrate a java program where we want to call parent class method. So
whenever a parent and child class have same named methods then to
referring sub class
resolve ambiguity. use super keyword
object
https://www.geeksforgeeks.org/multithreading-in-java/
2 Write the necessary classes with given member data and appropriate
methods by identifying the inherited properties from person class to patient
class and display all the details of patient.
2. Consider the following situation. A user would like to create a base class
that shouldn't be instantiated as a template for derived classes. S/he might
write something like
class Animal {
public age : number;
public yearsLeft() { return 20 - this.age; }
public makeSound() : string { return "???"; }
}
class Cow extends Animal {
makeSound() { return "Moo"; }
}
class Cat extends Animal {
makeSound() { return "Meow"; }
}
Today, the writer is forced to make a choice: either (i) Animal can be
declared an interface, but then yearsLeft cannot have an implementation, or
(ii) write the program as above, but then Animal can be instantiated and
makeSound has a bogus implementation! Neither of these options is
particularly attractive.
We propose abstract as a class declaration modifier to allow the programmer
control over whether a class can be instantiated, and as a member function
modifier to control whether said member function offers an implementation
(and whether the enclosing class is abstract).
Reference: https://github.com/microsoft/TypeScript/issues/3578
Write a java program which creates class A with private data members as
“data” . a private member function msg() and a public method hello().
Create a another class Simple which contains the main() and access the
private data “data”.
https://www.javatpoint.com/access-modifiers
2) User-defined packages
Write a java program which creates a student class in “pack” package .here
you define id,name,section name,email as data members, have a display().
And create another package Mypack place” test” class using import
statement import the student class print the details of student.
https://www.javatpoint.com/package
Write a java program which try to read data from the keyboard
using the Scanner class of the java.util package (like int float
,double,Boolean,string data)
https://www.tutorialspoint.com/what-is-a-predefined-
package-in-java
You are given a date. You just need to write the method, , which returns
the day on that date. To simplify your task, we have provided a portion of
the code in the editor.
For example, if you are given the date , the method should return as the
day on that date
https://www.hackerrank.com/challenges/java-date-and-
time/problem?h_r=internal-search
27 Interfaces and
implementing
interfaces
28
Extending
Interfaces
1. Exception Handling
Multiple https://www.hackerearth.com/practice/basic-
30
catch blocks, programming/implementation/basics-of-implementation/practice-
Nested try problems/algorithm/exception-handling-2-46f67551/
blocks
2. Nested try catch block in Java – Exception handling
https://beginnersbook.com/2013/04/nested-try-catch/
Throw, Throws 1. Exception handling is the process of responding to the occurrence, during
and finally blocks computation, of exceptions – anomalous or exceptional conditions requiring
31 User defined special processing – often changing the normal flow of program execution.
Exceptions (Wikipedia)
Java has built-in mechanism to handle exceptions. Using the try statement we
can test a block of code for errors. The catch block contains the code that says
what to do if exception occurs.
You will be given two integers x and y as input, you have to compute x/y . If x
and y are not 32- bit signed integers or if y is zero, exception will occur and
you have to report it. Read sample Input/Output to know what to report in case
of exceptions.
Sample Input 0:
10
3
Sample Output 0:
3
Sample Input 1:
10
Hello
Sample Output 1:
java.util.InputMismatchException
Sample Input 2:
10
0
Sample Output 2:
java.lang.ArithmeticException: / by zero
Sample Input 3:
23.323
0
Sample Output 3:
java.util.InputMismatchException
https://www.hackerrank.com/challenges/java-exception-handling-try-catch/problem
2. Read two numbers num1 and num2. Your goal is to find integer division. . If
Num1 or Num2 were not an integer, the program would throw a Number
Format Exception. If Num2 were Zero, the program would throw an
Arithmetic Exception.
33 Multithreading - 2 Sereja has an integer number A that doesn't contain zeroes in its decimal
form.
Also he has N integers B[1], B[2], ..., B[N].
URL : https://www.codechef.com/JAN15/problems/SEAND2
2) Multi Threads
Sheldon has just finished reading all his opened threads and refreshes
the main page for some more messages to feed his addiction. He notices
that no new threads have appeared in the list and at the i-th place in the
list there is a thread that was at the ai-th place before the refresh. He
doesn't want to waste any time reading old messages so he wants to open
only threads with new messages.
Help Sheldon find out the number of threads that surely have new
messages. A thread x surely has a new message if there is no such
sequence of thread updates (posting messages) that both conditions hold:
URL : https://www.codechef.com/PROM2013/problems/PT2
1) Java Arraylist
Introduction to Sometimes it's better to use dynamic size arrays. Java's Arraylist can
34
Collection provide you this feature. Try to solve this problem using Arraylist. You
Framework – Lists are given n lines. In each line there are zero or more integers. You need
to answer a few queries where you need to tell the number located in yth
position of xth line.
URL:https://www.hackerrank.com/challenges/java-
arraylist/problem?h_r=internal-search
Note: In this problem you must NOT generate any output on your own.
Any such solution will be considered as being against the rules and its
author will be disqualified. The output of your solution must be
generated by the uneditable code provided for you in the solution
template.
getDepth(): Returns the depth of the node. Recall that the depth of a
node is the number of edges between the node and the tree's root, so the
tree's root has depth and each descendant node's depth is equal to the
depth of its parent node +1.
URL:https://www.hackerrank.com/challenges/java-vistor-
pattern/problem
1. Madhuri wants to develop an app which sorts the Student Ids based
on marks (ascending). The User provides the marks of different
Introduction to
36 students along with student Ids and stores them in a HahMap. Help
Collection
him out writing the program to develop the app.
Framework – Map
2. Naresh wants you to develop a program which takes in words from
a list of movies names as dynamic user input and stores them in a
Hashset. It should then print them in lexicographical order after
converting Hashset into Treeset.