You are on page 1of 490

Introduction

Topic/Courseto JAVA
Sub-Topic (Example: name of college)

Program Internal
Why and How Java?
• History of Java

• Why Java?

• Where Java?

• Difference between JDK, JRE, JVM


Compiling our first Program
• Install the JDK if you don't have installed it.

• Set path of the jdk/bin directory.

• Create the java program (preferred notepad)

• Compile and run the java program (Assuming program is saved as Hello.java

• For compiling : javac Hello.java

• For executing : java Hello


1 public class Main
2 {
3 public static void main(String[] args)
4 {
5 System.out.println(“Welcome to FACE”);
6 }
7 }
8
9
10
11
12
13
14
15
Output
Welcome to FACE
During Compile time
After writing our first program, we compile them.

Hello.class can be used in different operating system


During runtime
Types of Java Application
• Standalone Application

• Web Application

• Enterprise Application

• Mobile Application
Types of Java Editions
• Java SE – Standard Edition

• Java EE – Enterprise Edition

• Java ME – Micro Edition

• JavaFX
JVM Architecture
• JVM gives the definitions …
• JVM works with …
• Memory area
• Loads code
• Class file format
• Verifies code
• Register set
• Executes code
• Garbage-collected heap
• Provides runtime Environment
• Fatal error reporting etc.
JVM Architecture
Path Setting
• Temporary Path

• Permanent Path

• Use of editors – Sublime editor, code block

• Notepad – Execute a program


Why is JAVA Platform Independent?
Why is JAVA both interpreted and
compiled language?
Why is JAVA both interpreted and
compiled language?
Why is JAVA slow?
THANK YOU
Path Setting - JAVA
Structure of Programming
Structure of Java program
• Documentation Section

• Package Statement

• Import Statements

• Interface Statement

• Class Definition

• Main Method Class

• Main Method Definition


1 //Sample Program Documentation Section
2 import java.util.* Import statement
3 interface MyInterface Interface statement
4 {
5 public void method();
6 }
7 class Sample implements MyInterface Main method class
8 {
9 public void method() Method definition
10 {
11 System.out.println(“Sample");
12 }
13 public static void main(String arg[]) Main method definition
14 {
15 MyInterface obj = new Demo();
16 obj.method();
17 }
18 }
19
20
21
22
Documentation Section
• Comment line

• Comments are beneficial for the programmer

• Optional

• Used in Corporate programs


Package Statement
• Package is a group of classes

• Optional

• Keyword

• if you want to declare many classes within one element, then you can
declare it within a package
Import Statement
• Keyword

• Used to import built-in and user-defined packages into your java source
file

• Use the '*' character to declare all the classes belonging to the package.

• Can import both Built in packages and user defined packages


Interface Statement
• Keyword

• Optional

• Similar to classes

• Includes a group of method declarations

• Can be used when programmers want to implement multiple inheritances


within a program
Class Definition
• Java can contain multiple classes

• Class is the most important segment inside a java program

• A class declaration is made up of the following parts:

• Modifiers • Keywords

• Class name • Class body within curly brackets {}


Main method class
• Java stand-alone program requires the main method as the starting point
of the program

• There may be many classes in a Java program, and only one class defines
the main method

• Methods contain data type declaration and executable statements.


Question 1
Java source code is compiled into __________

A) Source code
B) Byte code
C) .obj
D) .exe
Question 2
Which of the tool is used to compile java code ?

A) java
B) javadoc
C) jar
D) javac
What is javac?
Question 3
Which of the following tool used to execute java code.

A) java
B) javadoc
C) jar
D) javac
Question 4
What is use of interpreter?

A) They convert bytecode to machine language code


B) They read high level code and execute them
C) They are intermediated between JIT and JVM
D) It is a synonym for JIT
Question 4
What is use of interpreter?

A) They convert bytecode to machine language code


B) They read high level code and execute them
C) They are intermediated between JIT and JVM
D) It is a synonym for JIT
THANK YOU
Data Types
Data Types

Primitive data-types Non-primitive data-types


•byte •Strings
•int •Arrays
•short •Classes ….
•long
•char
•Boolean
•float
•double
Primitive Data Types
byte 1 byte Stores whole numbers from -128 to 127

int 4 bytes Stores whole numbers from -2,147,483,648 to 2,147,483,647

short 2 bytes Stores whole numbers from -32,768 to 32,767

long 8 bytes Stores whole numbers from -9,223.372,036.854,775.808 to


9,223.372,036,854,775,808
char 2 bytes Stores a single character/letter

boolean 1 byte Stores true or false values

float 4 bytes Stores fractional numbers from 3.4e−038 to 3.4e+038. Sufficient


for storing 6 to 7 decimal digits
double 8 bytes Stores fractional numbers from 1.7e−308 to 1.7e+038. Sufficient
for storing 15 decimal digits
BYTE
• Byte stores from -128 and 127.

• Can be used instead of int or other integer types to save memory.

byte myNum = 100;


System.out.println(myNum);
SHORT
• short stores from -32768 to 32767:

short myNum = 5000;


System.out.println(myNum);
INT
• int stores from -2147483648 to 2147483647.

• preferred data type when we create variables with a numeric value.

int myNum = 100000;


System.out.println(myNum);
LONG
• long stores from -9223372036854775808 to
9223372036854775808.

• Used when int is not large enough to store the value.

• you should end the value with an "L":

long myNum = 15000000000L;


System.out.println(myNum);
Floating Point Types
FLOAT
• float can store fractional numbers from 3.4e−038 to 3.4e+038.

• should end the value with an "f":


float myNum = 5.75f;
System.out.println(myNum);
DOUBLE
• Double can store fractional numbers from 1.7e−308 to 1.7e+038.

• you should end the value with a "d":

double myNum = 19.99d;


System.out.println(myNum);
Use float or double?
BOOLEAN
• declared with the boolean keyword

• can only take the values true or false:

boolean isJavaFun = true;


boolean isFishTasty = false;
System.out.println(isJavaFun);
System.out.println(isFishTasty);
STRING
• The String data type is used to store a sequence of characters (text).

• String values must be surrounded by double quotes:

String greeting = "Hello World";


System.out.println(greeting);
CHARACTER
• The char data type is used to store a single character.

• A char value must be surrounded by single quotes, like 'A' or 'c':

char myGrade = 'B';


System.out.println(myGrade);
WHY CHAR REQUIRES 2 BYTES IN JAVA?
IS STRING A NINTH TYPE?
WHY DO WE NEED DATA-TYPES?
IS IT REQUIRED ?
VARIABLES
What is a variable ?
• A variable which holds value, during the life of a Java program.

•Every variable is assigned a data type which designates the type and
quantity of value it can hold.

•In order to use a variable in a program you to need to perform 2 steps


--Variable Declaration
--Variable Initialization
Variable Declaration
To declare a variable, you must specify the data type & give the variable a
unique name.

Variable-
Data-type
name

int count;
Variable Initialization Container
named “count”
holding a value
To initialize a variable, you must assign it a valid value. 100

count=100;
100

count
You can combine variable declaration and initialization.

int count=100;
NAMING CONVENTION OF VARIABLES
• can start with underscore(‘_’) but not with digits.

• Should be mnemonic i.e, designed to indicate to the casual observer the


intent of its use.

• Can use _(underscore), digits and letters.

• Should not use any reserved word.


TYPES OF VARIABLES

Local variables Instance variables Static variables


Consider this code snippet
class Guru99
{
int data = 99; //instance variable
static int a = 1; //static variable
void method()
{
int b = 90; //local variable
}
}
Non-static variable V/S Static variable
Non-static variable Static variable

1. Memory is allocated multiple time 1. Memory is allocated for these


whenever a new object is created. variable only once in the program.
2. Non-static variable also known as 2. Memory is allocated at the time
instance variable while because of loading of class so that these
memory is allocated whenever are also known as class variable.
instance is created. 3. Static variable are common for
3. Non-static variable are specific to every object that means there
an object memory location can be sharable
4. Non-static variable can access by every object reference or same
with object reference. class.
4. Static variable can access with
class reference.
WHAT IS WIDENING?
Consider this code snippet
public class Test Can you predict the output?
{
public static void main(String[] args) YOLO
{
System.out.print("Y" + "O");
System.out.print('L' + 'O'); YO155
}
}
Now, try to predict the output
public class Test
{
public static void main(String[] args) YO7679
{
System.out.print("Y" + "O");
YOLO
System.out.print('L');
System.out.print('O');
}
}
RULES FOR WIDENING PRIMITVE CONVERSION
• The result of adding Java chars, shorts or bytes is an int.
• If either operand is of type double, the other is converted to
double.
• Otherwise, if either operand is of type float, the other is
converted to float.
• Otherwise, if either operand is of type long, the other is
converted to long.
• Otherwise, both operands are converted to type int
WHAT IS NARROWING?
NARROWING OR EXPLICIT TYPE-CASTING
If we want to assign a value of larger data type to a smaller data
type we perform explicit type casting or narrowing.

•This is useful for incompatible data types where automatic conversion


cannot be done.

•Here, target-type specifies the desired type to convert the specified


value to.
Guess the output
public class Test
{
public static void main(String[] argv) Error
{
char ch = 'c';
int num = 88;
ch = num;
}
}
Now, try to predict the output
class Simple
{
public static void main(String[] args)
{
float f=10.5f;
//int a=f;//Compile time error
10.5
int a=(int)f; 10
System.out.println(f);
System.out.println(a);
}
}
THANK YOU
Classes and Objects
Class

• Entity binding Data member and Member methods in one single unit

• Data Member(Properties)

• Member Methods(Behavior)
Class
In other words class is said to be a blueprint or a template.

Why we use class Framework?


Example
To build a home the first thing we need to do is,

Blueprint

Then comes the Real House


Class Name Object
Attribute 1
Attribute 2 Heap Storage where
…… attributes are to be stored.
Method 1
Method 2
….
1 //Program Explanation
2 blade_info;
3 Class Fan motor_info;
4 { switch;
5 blade_info; regulator;
6 motor_info; These are said to be
7 switch; state(Variables)
8 regulator;
9 blade_design(); blade_design()
10 motor_design(); motor_design()
11 { These are said to be
12 …………… behavior(action)
13 }
14 switch_operate(); Fan is said to be the classname
15 speed_control(); and f is said to be the object.
16 } The classname is the user
17 Fan f; defined datatype.
18 The memory is allocated in class
19 declaration.
20
21
22
Objects
Object is a real time entity.

Multiple objects can be created for a single class.

The object can be both non-living and living objects.

Objects can be of unique specifications and characteristic behavior or


functionality.
Example
If we consider a TV
The Attributes can be display,volume
The Functionalities can be on/off and low/high.

Similarly if we consider a dog in general,


The attributes are food,breed,cost,color,reliability
The functionalities are bark.sleep,eat,walk
Static and Non-Static Members
Static Methods

Non static Methods


1 //Program 23 public void sum()
2 24 {
3 public class demo 25 int a = 90;
4 { 26 int b = 100;
5 int x = 90; 27 int c = a + b;
6 int y = 100; 28 System.out.println(c);
7 public static void main(String 29 }
8 args[]) 30
9 { 31
10 System.out.println(“HAI”); 32
11 demo obj = new demo(); 33
12 obj.sum(); 34
13 System.out.println(obj.x); 35
14 System.out.println(obj.y); 36
15 System.out.println(“Hello”); 37
16 } 38
17 39
18 40
19 41
20
21
22
1 Class A
2 {
3 public static void main(String args[])
4 {
5 byte i = 10;
6 byte j = 20;
7 byte k = i + j;
8 System.out.println(k);
9 }
10 }
11
12
13
14
15
Output
Error: incompatible types: possible lossy conversion from int to byte
1 Class A
2 {
3 public static void main(String args[])
4 {
5 int i = ‘d’;
6 System.out.println(i);
7 }
8 }
9
10
11
12
13
14
15
Output
100
1 Class A
2 {
3 public static void main(String args[])
4 {
5 int i = 028;
6 System.out.println(i);
7 }
8 }
9
10
11
12
13
14
15
Output
Error
1 Class A
2 {
3 public static void main(String args[])
4 {
5 int i = 035;
6 System.out.println(i);
7 }
8 }
9
10
11
12
13
14
15
Output
29
1 public class A
2 {
3 public static void main(String args[])
4 {
5 System.out.println(‘j’ + ’a’ + ’v’ + ’a’);
6 }
7 }
8
9
10
11
12
13
14
15
Output
418
1 public class A
2 {
3 public static void main(String args[])
4 {
5 if(true)
6 break;
7 }
8 }
9
10
11
12
13
14
15
Output
Error
THANK YOU
Operators
Topic/Course
Sub-Topic (Example: name of college)
Operators are used to perform operations on variables and values.

Topic/Course
Sub-Topic (Example: name of college) operators
• Unary operators
X=Y–1
• Binary operators

• Ternary operators
operands
Operators in Java
• Unary operators • Logical operators
• Arithmetic operators • Ternary operators
• Relational operators • Assignment operators
• Bitwise operators • instanceof operator
Unary operators

• Unary operator performs operation on only one operand.


• They are used to increment, decrement or negate a value.
Unary operators
Operator Description Example
++x(prefix)
++ Increases the value of a variable by 1
x++(postfix)
--x(prefix)
-- Decreases the value of a variable by 1
x--(postfix)
+ Used for giving positive values +x

- Used for negating the values -x

~ Negating an expression ~x

! Inverting the value of a boolean !x


What is the difference between
++x and x++ ?
1 class OperatorExample{ output
2 public static void main(String args[]){
3
4 int x=10; 10
5 System.out.println(x++); 12
6 System.out.println(++x); 12
7 System.out.println(x--); 10
10 System.out.println(--x);
11 }
12 }
1 class OperatorExample{ output
2 public static void main(String args[]){
3 int a=10;
4 int b=-10; -11
5 boolean c=true; 9
6 boolean d=false; False
7 System.out.println(~a); true
10 System.out.println(~b);
11 System.out.println(!c);
12 System.out.println(!d);
13 }
14 }
Arithmetic operators

• Arithmetic operators are used to perform common mathematical


operations like addition, subtraction etc..
Arithmetic operators
Operator Description Example
+ Adds two values x+y

- Subtracts one value from another x-y

* Multiplies two values x*y

/ Returns the division quotient x/y

% Returns the division remainder x%y


What is the difference between
/ and % ?
1 class OperatorExample{
2 public static void main(String args[]){
3 int a=10;
4 int b=5;
5 System.out.println(a+b);
6 System.out.println(a-b);
7 System.out.println(a*b);
10 System.out.println(a/b);
11 System.out.println(a%b);
12 }
13 }

output

15
5
50
2
0
Relational operators

• Relational/Comparison operators are used to compare two values.

• They return boolean result after the comparison.


Relational operators
Operator Description Example
== Returns true if left hand side is equal to right hand side x == y
Returns true if left hand side is not equal to right hand
!= x != y
side
< Returns true if left hand side is less than right hand side x<y
Returns true if left hand side is less than or equal to
<= x < =y
right hand side
Returns true if left hand side is greater than right hand
> x >=y
side
Returns true if left hand side is greater than or equal to
>= x >= y
right hand side
1 public class Test { output
2 public static void main(String args[]){
3 int a = 10;
4 int b = 20; false
5 System.out.println(a>b); true
6 System.out.println(a<b); false
7 System.out.println(a>=b); true
10 System.out.println(a<=b); false
11 System.out.println(a==b); true
12 System.out.println(a!=b);
13 }
14 }
Bitwise operators

• Bitwise operator works on bits and performs bit-by-bit operation.

• Can be applied to the integer types, long, int, short, char, and byte.
Bitwise operators
Operator Description Example
& Returns bit by bit AND of input values x&y

| Returns bit by bit OR of input values x|y

^ Returns bit by bit XOR of input values x^y

~ Returns the one’s compliment representation of the input value ~x

<< shifts the bits of the number to the left and fills 0 on voids left as a result x << 2

>> shifts the bits of the number to the right x >> 2

>>> shifts the bits of the number to the right and fills 0 on voids left as a result x >>>2
1 public class Main { output
2 public static void main(String args[]){
3 int a = 10;
4 int b = 20; 0
5 System.out.println(a&b); 30
6 System.out.println(a|b); -11
7 System.out.println(~a); 40
10 System.out.println(a<<2); 2
11 System.out.println(a>>2); 2
12 System.out.println(a>>>2);
13 }
14 }
Logical operators

• The logical operators || (conditional-OR) and && (conditional-AND)


operates on boolean expressions.

• The second condition is not evaluated if the first one is false, i.e. it has a
short-circuiting effect.
Logical operators
Operator Description Example
&& Returns true if both statements are true x < 5 && x < 10

|| Returns true if one of the statements is true x < 5 || x < 4

! Reverse the result, returns false if the result is true !(x < 5 && x < 10)
1 public class Test { output
2 public static void main(String args[]){
3 boolean a = true;
4 boolean b = false; false
5 System.out.println(a&&b); true
6 System.out.println(a||b); true
7 System.out.println(!(a && b));
10 }
11 }
Ternary operator

• Ternary/Conditional operator consists of three operands and is used to


evaluate Boolean expressions.
• Ternary operator is a shorthand version of if-else statement.
• It has three operands and hence the name ternary.
1 class OperatorExample{ output
2 public static void main(String args[]){
3 int a=2;
4 int b=5; 2
5 int min=(a<b)?a:b;
6 System.out.println(min);
7 }
10 }
Assignment operators
• Assignment operator is used to assign a value to any variable.

• In many cases assignment operator can be combined with other


operators to build a shorter version of statement called Compound
Statement.
Assignment operators
Operator Description Example
= Assigns values from right side operands to left side operand. C=A+B

+= Adds right operand to the left operand and assign the result to left operand. C += A
Subtracts right operand from the left operand and assign the result to left
-= C -= A
operand.
Multiplies right operand with the left operand and assign the result to left C *= A
*=
operand.
Divides left operand with the right operand and assign the result to left C /= A
/=
operand.
%= Takes modulus using two operands and assign the result to left operand. C %= A
Assignment operators
Operator Description Example
<<= Left shift AND assignment operator C <<= 2

>>= Right shift AND assignment operator C >>= 2

&= Bitwise AND assignment operator C &= 2

^= Bitwise exclusive OR and assignment operator C ^= 2

|= Bitwise inclusive OR and assignment operator C |= 2


What is the difference between
= and == ?
1 class OperatorExample{ output
2 public static void main(String[] args){
3 int a=10;
4 a+=3; 13
5 System.out.println(a); 9
6 a-=4; 18
7 System.out.println(a); 9
10 a*=2;
11 System.out.println(a);
12 a/=2;
13 System.out.println(a);
14 }
15 }
instanceof operators
• instanceof operator is used only for object reference variables.

• The operator checks whether the object is of a particular type (class type
or interface type).
1 public class Test { output
2 public static void main(String args[]) {
3 String name = "James";
4 boolean result = name instanceof String;
5 System.out.println( result ); true
6 }
7 }
10
11
Precedence and associativity
• Operator precedence determines which operator is evaluated first when
an expression has more than one operators.

• Associativity is used when there are two or more operators of same


precedence is present in an expression.
1 // Predict the output
2 public class A {
3 public static void main(String[] args)
4 {
5 int $_ = 5;
6 }
7 }
OUTPUT

1. Nothing
2. Error
1 // Predict the output
2 class Test {
3 public static void main(String args[]) {
4 System.out.println(10 + 20 + “Face");
5 System.out.println(“Face" + 10 + 20);
6 }
7 }
OUTPUT

1. 30Face Face30
2. 1020Face Face1020
3. 30Face Face1020
4. 1020Face Face30
1 // Predict the output
2 class Test
3 {
4 public static void main(String args[])
5 {
6 String s1 = “FACE";
7 String s2 = “FACE";
8 //System.out.println(s1==s2);
9 System.out.println("s1 == s2 is:" + s1 == s2);
10 }
}
OUTPUT

1. true
2. false
3. compiler error
4. throws an exception
THANK YOU
Write a program to perform Arithmetic operations such as addition,
subtraction, multiplication and division.

Sample Input: Sample Output:


5 7
2 3
10
1
2
1 import java.util.Scanner;
2 class Main
3
4 {
5 public static void main (String[] args)
6 {
7 Scanner in = new Scanner(System.in);
8
9 int a = in.nextInt();
10 int b = in.nextInt();
11 System.out.println(a+b);
12 System.out.println(a-b);
13
14 System.out.println(a*b);
15 System.out.println(a/b);
16 System.out.println(a%b);
17 }
18
19 }
20
21
22
There was a large ground in center of the city which is rectangular in shape. The
Corporation decides to build a cricket stadium in the area for school and college
students, But the area was used as a car parking zone. In order to protect the land
from using as an unauthorized parking zone , the corporation wanted to protect the
stadium by building a fence. In order to help the workers to build a fence, they
planned to place a thick rope around the ground. They wanted to buy only the
exact length of the rope that is needed. They also wanted to cover the entire
ground with a carpet during rainy season. They wanted to buy only the exact
quantity of carpet that is needed. They requested your help.
Can you please help them by writing a program to find the exact length of the rope
and the exact quantity of carpet that is required?
Sample Input: Sample Output:
5 22
6 30
1 import java.util.Scanner;
2 class Main
3
4 {
5 public static void main (String[] args)
6 {
7 Scanner in = new Scanner(System.in);
8
9 int l = in.nextInt();
10 int b = in.nextInt();
11 System.out.println(2*(l+b));
12 System.out.println(l*b);
13
14 }
15 }
16
17
18
19
20
21
22
Alice wanted to start a business and she was looking for a venture capitalist. Through her
friend Bob she went to a the owner of a Construction company who is looking to invest on
a emerging business. Looking after the business proposal , the owner was very much
impressed with Alice work. He wanted to invest in Alice Business. So he gives a green
signal to go ahead with the project. Alice bought Rs.X for a period of Y years from the
owner at R% interest per annum. Find the rate of interest and the total amount to be given
by Alice to the owner. The owner impressed by proper repayment of the financed amount
decides to give a special offer of 2% discount in the total interest at the end of the
settlement. Find the amount given back by Alice and also find total amount. (Note. All
rupees value should be in two decimal points).

Sample Input: Sample Output:


100 10.00
1 110.00
10 0.20
109.80
1 import java.util.Scanner;
2 class Main
3 {
4 public static void main (String[] args)
5 {
6 Scanner in = new Scanner(System.in);
7 int amt = in.nextInt();
8 int intr = in.nextInt();
9 int years = in.nextInt();
10 float a=0,b=0,c=0,d=0;
11 a=(amt*years*intr)/100;
12 b=amt + a;
13 c=(a*2)/100;
14 d=b-c;
15 System.out.printf("%.2f\n",a);
16 System.out.printf("%.2f\n",b);
17 System.out.printf("%.2f\n",c);
18 System.out.printf("%.2f\n",d);
19 }
20 }
21
22
The Training for sports day has begun and Physical education teacher has decided
to conduct some team games. The teacher wants to split the students in the Higher
Secondary into equal sized teams. In some cases, there may be some students who
are left out from teams and he wanted to use the left out students to assist him in
conducting the team games.For instance, if there are 50 students in the class and if
the class has to be divided into 7 equal sized teams, 7 students will be there in each
team and 1 student will be left out.PET asks your help to automate this team
splitting task. Can you please help him out?

Sample Input: Sample Output:


60 7
8 4
1 import java.util.Scanner;
2 class Main
3
4 {
5 public static void main (String[] args)
6 {
7 Scanner in = new Scanner(System.in);
8
9 int a = in.nextInt();
10 int b = in.nextInt();
11 System.out.println(a/b);
12 System.out.println(a%b);
13
14 }
15 }
16
17
18
19
20
21
22
A young man named d'Artagnan leaves home to travel to Paris, to join the Musketeers of
the Guard. Although D'Artagnan is not able to join this elite corps immediately, he befriends
the three most formidable musketeers of the age: Athos, Porthos and Aramis and gets
involved in affairs of the state and court.At that time, the cardinal was planning to dethrone
the king and to take the kingdom and to remove the musketeers of the guard. Since the
cardinal has spies mixed with the local public , d'Artagnan decides to send a message of his
whereabouts to the three musketeers in unique way.He gave a note to a boy which has the
following message. I am at the midpoint of the line joining the farmhouse next to the palace
and the light house. The Three musketeers were puzzled. Can you help them find out the
location of d'Artagnan?Given the coordinates of the 2 places (x1,y1) and (x2,y2), write a
program to find the location of d'Artagnan.

Sample Input: Sample Output:


2 6.0
4 9.5
10
15
1 import java.util.Scanner;
2 class Main
3 {
4 public static void main (String[] args)
5 {
6 Scanner in = new Scanner(System.in);
7 float x1 = in.nextFloat();
8 float y1 = in.nextFloat();
9 float x2 = in.nextFloat();
10 float y2 = in.nextFloat();
11 float p1=0,p2=0;
12 p1=(x1+x2)/2;
13 p2=(y1+y2)/2;
14 System.out.printf("%.1f\n",p1);
15 System.out.printf("%.1f",p2);
16 }
17 }
18
19
20
21
22
Each Sunday, a newspaper agency sells w copies of a special edition
newspaper for Rs.x per copy. The cost to the agency of each newspaper
is Rs.y . The agency pays a fixed cost for storage, delivery and so on of
Rs.100 per Sunday. The newspaper agency wants to calculate the profit
which it obtains only on sundays. Can you please help them out by
writing a program to compute the profit given w, x and y.

Sample Input: Sample Output:


1000 900
2
1
1 import java.util.Scanner;
2 class Main
3 {
4 public static void main (String[] args)
5 {
6 Scanner in = new Scanner(System.in);
7 int a = in.nextInt();
8 int b = in.nextInt();
9 int c = in.nextInt();
10 int result=0;
11 result=((a*b)-(a*c)-100);
12 System.out.println(result);
13 }
14 }
15
16
17
18
19
20
21
22
Four kids Peter,Susan,Edmond and Lucy travel through a wardrobe to the land of
Narnia. Narnia is a fantasy world of magic with mythical beasts and talking animals.While
exploring the land of narnia Lucy found Mr.Tumnus the two legged stag ,and she followed
it, down a narrow path .She and Mr.Tumnus became friends and he offered a cup of coffee
to Lucy in his small hut.It was time for Lucy to return to her family and so she bid good bye
to Mr.Tumnus and while leaving Mr.Tumnus told that it is quite difficult to find the route
back as it was already dark.He told her to see the trees while returning back and said that
the first tree with two digits number will help her find the way and the way to go back to
her home is the sum of digits of the tree and that numbered way will lead her to the tree
next to the wardrobe where she can find the others.Lucy was already confused, so pls
help her in finding the route to her home....

Sample Input: Sample Output:


23 5
1 import java.util.Scanner;
2 class Main
3 {
4 public static void main (String[] args)
5 {
6 Scanner in = new Scanner(System.in);
7 int a = in.nextInt();
8 int sum=0,b=0,c=0;
9 b=a/10;
10 c=a%10;
11 sum=b+c;
12 System.out.println(sum);
13 }
14 }
15
16
17
18
19
20
21
22
Long ago , there was a war between the Trojans and Greeks.The Trojan and Greek
armies meet outside the walls of Troy. Seeing the bloodshed the two kings to
decide to end the battle as early as possible as both the armies suffer a lot.
The shape of the battle ground is Square. To win the war is to conquer the flag first
by the opposite army , it has been decided to place the flag post at the exact center
of the battle field. Can you please help them in placing the flag post at the exact
center? Given the coordinates of the left bottom vertex of the square ground and
the length of the side of the battle field, you need to write a program to determine
the coordinates of the centre of the ground.
[Assumption --- Length of the side is always even]

Sample Input: Sample Output:


4 8
0 4
8
1 import java.util.Scanner;
2 class Main
3 {
4 public static void main (String[] args)
5 {
6 Scanner in = new Scanner(System.in);
7 int x = in.nextInt();
8 int y = in.nextInt();
9 int l = in.nextInt();
10 int a=0,b=0;
11 a=x+(l/2);
12 b=y+(l/2);
13 System.out.println(a);
14 System.out.println(b);
15 }
16 }
17
18
19
20
21
22
d'Artagnan also joined the group of 3musketeers and now their group is calledFour
Musketeers. Meanwhile, d'Artagnan also moved to a new house in the same locality nearby
to the other three. Now the houses of Athos, Porthos and Aramis are located in the shape
of a triangle. Dinesh also has moved to a house in the same locality. When the three
musketeers asked d'Artagnan about the location of his house , he said that his house is
equidistant from the houses of the other 3. Can you please help them find out the location
of the house?Given the 3 locations {(x1,y1), (x2,y2) and (x3,y3)} of a triangle, write a
program to determine the point which is equidistant from all the 3 points.

Sample Input: Sample Output:


2 5.7
4 9.0
10
15
5
8
1 import java.util.Scanner;
2 class Main
3 {
4 public static void main (String[] args)
5 {
6 Scanner in = new Scanner(System.in);
7 int x1 = in.nextInt();
8 int y1 = in.nextInt();
9 int x2 = in.nextInt();
10 int y2 = in.nextInt();
11 int x3 = in.nextInt();
12 int y3 = in.nextInt();
13 float a=0,b=0;
14 a=(x1+x2+x3)/3.0f;
15 b=(y1+y2+y3)/3.0f;
16 System.out.printf("%.1f\n",a);
17 System.out.printf("%.1f",b);
18 }
19 }
20
21
22
Mrs.Bhulbhul is a miser to the core.She saves money even on petite
things. One dayshe heard a discount offer announced in a mall. she
wants to purchase lot of items to save her money. The discount is given
only when atleast two items are bought. Since each item has
different discount prices , she finds difficult to check the amount she has
saved. So she approaches you to device a automated discount calculator
to make her easy while billing.

Sample Input: Sample Output:


20.50 65.90
45.40 59.31
10 6.59
1 import java.util.Scanner;
2 class Main
3 {
4 public static void main (String[] args)
5 {
6 Scanner in = new Scanner(System.in);
7 float a = in.nextFloat();
8 float b = in.nextFloat();
9 float c = in.nextFloat();
10 float x=0,y=0,y1=0,z=0;
11 x=a+b;
12 System.out.printf("%.2f\n",x);
13 y=x*c/100;
14 y1=x-y;
15 System.out.printf("%.2f\n",y1);
16 z=x*c/100;
17 System.out.printf("%.2f",z);
18 }
19 }
20
21
22
Though there have been more successful pirates, Blackbeard is one of the best-known and
widely-feared of his time . He commanded four ships and had a pirate army of 300 at the
height of his career, and defeated the famous warship, HMS “Scarborough” in sea-battle.
He was known for barreling into battle clutching two swords, with several knives and
pistols at the ready. He captured over forty merchant ships in the Caribbean, and without
flinching killed many prisoners.Blackbeard and his three pirates found a treasure of gold
coinsLong Ben too joined them. They decided to share the treasure. Blackbeard agreed to
give x % share for Long Ben. He then decided to take y % share from the remaining
treasure. His other pirates willl share equally the remaining gold coins. Write a program to
compute their share's.

Sample Input: Sample Output:


500 125
25 123
33 84
1 import java.util.Scanner;
2 class Main
3 {
4 public static void main (String[] args)
5 {
6 Scanner in = new Scanner(System.in);
7 int a = in.nextInt();
8 int b = in.nextInt();
9 int c = in.nextInt();
10 int d=0,e=0,f=0;
11 d=(a*b)/100;
12 e=((a-d)*c)/100;
13 f=(a-(d+e))/3;
14 System.out.println(d);
15 System.out.println(e);
16 System.out.println(f);
17 }
18 }
19
20
21
22
My name is Booka and I’m an alien.
I couldn't understand how you measure days, weeks, months and year.
Please make me to understand about the days, weeks, months and year.
Dear Friend,
Make Booka to understand what is meant by days,week, months and
year. Teach him about the conversion of days in to years, weeks and days
using a program.

Sample Input: Sample Output:


373 1
1
1
1 import java.util.Scanner;
2 class Main
3
4 {
5 public static void main (String[] args)
6 {
7 Scanner in = new Scanner(System.in);
8
9 int a = in.nextInt();
10 int x=0,y=0,z=0,m=0;
11 x=a/365;
12 y=a-(x*365);
13
14 z=y/7;
15 m=y-z*7;
16 System.out.println(x);
17 System.out.println(z);
18
19 System.out.println(m);
20 }
21 }
22
Having crossed the three headed dog Harry , Ron and Hermoine went through a secret trap
door in search of Sorcerer's stone .One the way they passed through a room and found that
the room has only one door opposite to them and the door through which they entered has
shut once they entered the room. The door was very large with a four digit number
imprinted on it . When Harry and Ron tried to open it by casting out spells , it didn't open ,
having tried various spells both of them got fed up and they left the task to Hermoine.
Hermoine on curiously observing the room found that a statement was written on the top of
the room.It was written as follows
" I will be always four.
“I can only be opened when you add my first and last and enter it”
“If you find a sign , you should not consider it”
Help Hermoine to break the code and open the door so that they can save the sorcerer's
stone.

Sample Input: Sample Output:


1001 2
1 import java.util.Scanner;
2 class Main
3 {
4 public static void main (String[] args)
5 {
6 Scanner in = new Scanner(System.in);
7 int a = in.nextInt();
8 int x=0,y=0;
9 x=a/1000;
10 y=a%10;
11 System.out.println(x+y);
12 }
13 }
14
15
16
17
18
19
20
21
22
Big Bunny lives in a colony , he is the only bunny in his colony who was
not able to hop. On his 5th birthday, his father bunny gifted him a Pogo
Stick as he could not jump like the other bunnies. He is so excited to play
with pogo stick. The pogo stick hops one unit per jump. He wanders
around his house jumping with pogo sticks. He wants to show the pogo
stick to his friends and decide to go using pogo sticks. Write a program
to find number of hops needed to reach his friends house. Assume that
Big Bunny's house is in the location (3,4).

Sample Input: Sample Output:


5 2
6
1 import java.util.Scanner;
2 class Main
3 {
4 public static void main (String[] args)
5 {
6 Scanner in = new Scanner(System.in);
7 int x = in.nextInt();
8 int y = in.nextInt();
9 int x1=0,y1=0;
10 x1=x-3;
11 y1=y-4;
12 if(x1 > y1)
13 System.out.print(x1);
14 else
15 System.out.print(y1);
16 }
17 }
18
19
20
21
22
Wind chill factor is the felt air temperature on exposed skin due to wind.
The wind chill temperature is always lower than the air temperature, and
is calculated as per the following formula.
wcf = 35.74 + 0.6215t + (0.4275t - 35.75) * v^0.16
Write a program to receive values of temperature and wind velocity and
calculate wind chill factor.

Sample Input: Sample Output:


35 23.92
20
1 import java.util.Scanner;
2 class Main
3 {
4 public static void main (String[] args)
5 {
6 Scanner in = new Scanner(System.in);
7 int temp = in.nextInt();
8 int vel = in.nextInt();
9 double wcf=0;
10 wcf = 35.74 + 0.6215 * temp + (0.4275*temp - 35.75) *
11 Math.pow(vel,0.16);
12 System.out.printf("%.2f",wcf);
13 }
14 }
15
16
17
18
19
20
21
22
THANK YOU
PRINTING
• There are three standard streams, all are managed by the
java.lang.System class
• Standard input--referenced by System.in
– Used for program input, typically reads input entered by the user.
• Standard output--referenced by System.out
– Used for program output, typically displays information to the user.
• Standard error--referenced by System.err
– Used to display error messages to the user.
PRINTING
The basic output statement is :
System.out.println( );

Others methods:

1. System.out.println()
2. System.out.print()
3. System.out.printf()
Let us see an example

class AssignmentOperator
{
public static void main(String[] args)
{
System.out.println("Java programming.");
}
}
Difference between print(), println() and printf()

•print() - prints string inside the quotes.

•println() - prints string inside the quotes similar like print() method. Then
the cursor moves to the beginning of the next line.

•printf() - it provides string formatting.


Guess the output
class Output
{
public static void main(String[] args)
{
System.out.println("1. println ");
System.out.println("2. println ");
System.out.print("1. print ");
System.out.print("2. print");
}
}
PRINTING VARIABLES AND LITERALS
To display integers, variables and so on, do not use quotation marks.

class Variables
{
public static void main(String[] args)
{
Double number = -10.6;
System.out.println(5);
System.out.println(number);
}
}
Print concatenated strings
You can use + operator to concatenate strings and print it.

class PrintVariables
{
public static void main(String[] args)
{
Double number = -10.6;
System.out.println("I am " + "awesome.");
System.out.println("Number = " + number);
}
}
Consider this code snippet

int a = 3;
int b = 4;
System.out.println( a + b );
System.out.println( "3" + "4" );
System.out.println( "" + a + b );
System.out.println( 3 + 4 + a + " " + b + a );
System.out.println( "Result: " + a + b );
System.out.println( "Result: " + ( a + b ) );
Printing characters
You can use + operator to concatenate strings and print it.

char a=65;
char b='A';
System.out.println(a);
System.out.println(b);
READING INPUT
READING INPUT FROM CONSOLE
In Java, there are three different ways for reading input from
the user in the command line environment(console).

1. Using Buffered Reader Class


2. Using Scanner Class
3. Using Console Class
BUFFERED READER CLASS
This method is used by wrapping the System.in (standard input
stream) in an InputStreamReader which is wrapped in a
BufferedReader, we can read input from the user in the
command line.
BUFFERED READER CLASS
import java.io.BufferedReader; // Reading data using readLine
import java.io.IOException; String name = reader.readLine();
import java.io.InputStreamReader;
public class Test // Printing the read line
{ System.out.println(name);
public static void main(String[] args) }
throws IOException }
{
//Enter data using BufferReader
BufferedReader reader =
new BufferedReader(new
InputStreamReader(System.in));
SCANNER CLASS

•This is probably the most preferred method to take input.

• The main purpose of the Scanner class is to parse primitive types and strings
using regular expressions, however it is also can be used to read input from
the user in the command line.
SCANNER CLASS
import java.util.Scanner; int a = in.nextInt();
System.out.println("You entered
class GetInputFromUser integer "+a);
{
public static void main(String args[]) float b = in.nextFloat();
{ System.out.println("You entered
// Using Scanner for Getting Input float "+b);
from User }
Scanner in = new }
Scanner(System.in);
String s = in.nextLine();
System.out.println("You entered
string "+s);
CONSOLE CLASS

• It has been becoming a preferred way for reading user’s input from the
command line.

• In addition, it can be used for reading password-like input without echoing


the characters entered by the user; the format string syntax can also be used
(like System.out.printf()).
CONSOLE CLASS
public class Sample
{
public static void main(String[] args)
{
// Using Console to input data from user
String name = System.console().readLine();

System.out.println(name);
}
}
COMMAND LINE ARGUMENTS
COMMAND LINE ARGUMENTS
The java command-line argument is an argument i.e. passed at
run time.

The arguments passed from the console can be received in the


java program and it can be used as an input.
Let us see an example

class CommandLineExample
{
public static void main(String args[])
{
System.out.println("Your first argument is: "+args[0]);
}
}
Program 1 : Adding two integers using command line arguments

class A
Predict the output .
{
public static void main(String args[]) 9
{
System.out.println(args[0]+args[1]);
} 18
}
Program 1 : Adding two integers using command line arguments

class A{
public static void main(String args[]) Predict the output .
{
9
System.out.println(Integer.parseInt(args[0])
+Integer.parseInt(args[1]));
}
}
Program 2 : Concatenating two strings

class A
{ Predict the output .
public static void main(String args[])
Hai Hello
{
System.out.println(args[0]+args[1]);
}
}
Program 3 : Find average of your marks (5 subjects)

class A
{
public static void main(String args[]) Predict the output .
{ Input : java A 67 98 91 78 98
float avg;
avg = (args[0]+args[1]+args[2]+args[3]+args[4])/5; 86.4
System.out.println(avg);
}
}
Program 3 : Find average of your marks (5 subjects)

class A
{
public static void main(String args[]) Predict the output .
{ Input : java A 67 98 91 78 98
float avg;
avg= 86.4
(Float.valueOf(args[0])+Float.valueOf(args[1])+
Float.valueOf(args[2])+Float.valueOf(args[3])+F
loat.valueOf(args[4]))/5;
System.out.println(avg);
}
}
THANK YOU
PRINTING
• There are three standard streams, all are managed by the
java.lang.System class
• Standard input--referenced by System.in
– Used for program input, typically reads input entered by the user.
• Standard output--referenced by System.out
– Used for program output, typically displays information to the user.
• Standard error--referenced by System.err
– Used to display error messages to the user.
PRINTING
The basic output statement is :
System.out.println( );

Others methods:

1. System.out.println()
2. System.out.print()
3. System.out.printf()
Let us see an example

class AssignmentOperator
{
public static void main(String[] args)
{
System.out.println("Java programming.");
}
}
Difference between print(), println() and printf()

•print() - prints string inside the quotes.

•println() - prints string inside the quotes similar like print() method. Then
the cursor moves to the beginning of the next line.

•printf() - it provides string formatting.


Guess the output
class Output
{
public static void main(String[] args)
{
System.out.println("1. println ");
System.out.println("2. println ");
System.out.print("1. print ");
System.out.print("2. print");
}
}
PRINTING VARIABLES AND LITERALS
To display integers, variables and so on, do not use quotation marks.

class Variables
{
public static void main(String[] args)
{
Double number = -10.6;
System.out.println(5);
System.out.println(number);
}
}
Print concatenated strings
You can use + operator to concatenate strings and print it.

class PrintVariables
{
public static void main(String[] args)
{
Double number = -10.6;
System.out.println("I am " + "awesome.");
System.out.println("Number = " + number);
}
}
Consider this code snippet

int a = 3;
int b = 4;
System.out.println( a + b );
System.out.println( "3" + "4" );
System.out.println( "" + a + b );
System.out.println( 3 + 4 + a + " " + b + a );
System.out.println( "Result: " + a + b );
System.out.println( "Result: " + ( a + b ) );
Printing characters
You can use + operator to concatenate strings and print it.

char a=65;
char b='A';
System.out.println(a);
System.out.println(b);
READING INPUT
READING INPUT FROM CONSOLE
In Java, there are three different ways for reading input from
the user in the command line environment(console).

1. Using Buffered Reader Class


2. Using Scanner Class
3. Using Console Class
BUFFERED READER CLASS
This method is used by wrapping the System.in (standard input
stream) in an InputStreamReader which is wrapped in a
BufferedReader, we can read input from the user in the
command line.
BUFFERED READER CLASS
import java.io.BufferedReader; // Reading data using readLine
import java.io.IOException; String name = reader.readLine();
import java.io.InputStreamReader;
public class Test // Printing the read line
{ System.out.println(name);
public static void main(String[] args) }
throws IOException }
{
//Enter data using BufferReader
BufferedReader reader =
new BufferedReader(new
InputStreamReader(System.in));
SCANNER CLASS

•This is probably the most preferred method to take input.

• The main purpose of the Scanner class is to parse primitive types and strings
using regular expressions, however it is also can be used to read input from
the user in the command line.
SCANNER CLASS
import java.util.Scanner; int a = in.nextInt();
System.out.println("You entered
class GetInputFromUser integer "+a);
{
public static void main(String args[]) float b = in.nextFloat();
{ System.out.println("You entered
// Using Scanner for Getting Input float "+b);
from User }
Scanner in = new }
Scanner(System.in);
String s = in.nextLine();
System.out.println("You entered
string "+s);
CONSOLE CLASS

• It has been becoming a preferred way for reading user’s input from the
command line.

• In addition, it can be used for reading password-like input without echoing


the characters entered by the user; the format string syntax can also be used
(like System.out.printf()).
CONSOLE CLASS
public class Sample
{
public static void main(String[] args)
{
// Using Console to input data from user
String name = System.console().readLine();

System.out.println(name);
}
}
COMMAND LINE ARGUMENTS
COMMAND LINE ARGUMENTS
The java command-line argument is an argument i.e. passed at
run time.

The arguments passed from the console can be received in the


java program and it can be used as an input.
Let us see an example

class CommandLineExample
{
public static void main(String args[])
{
System.out.println("Your first argument is: "+args[0]);
}
}
Program 1 : Adding two integers using command line arguments

class A
Predict the output .
{
public static void main(String args[]) 9
{
System.out.println(args[0]+args[1]);
} 18
}
Program 1 : Adding two integers using command line arguments

class A{
public static void main(String args[]) Predict the output .
{
9
System.out.println(Integer.parseInt(args[0])
+Integer.parseInt(args[1]));
}
}
Program 2 : Concatenating two strings

class A
{ Predict the output .
public static void main(String args[])
Hai Hello
{
System.out.println(args[0]+args[1]);
}
}
Program 3 : Find average of your marks (5 subjects)

class A
{
public static void main(String args[]) Predict the output .
{ Input : java A 67 98 91 78 98
float avg;
avg = (args[0]+args[1]+args[2]+args[3]+args[4])/5; 86.4
System.out.println(avg);
}
}
Program 3 : Find average of your marks (5 subjects)

class A
{
public static void main(String args[]) Predict the output .
{ Input : java A 67 98 91 78 98
float avg;
avg= 86.4
(Float.valueOf(args[0])+Float.valueOf(args[1])+
Float.valueOf(args[2])+Float.valueOf(args[3])+F
loat.valueOf(args[4]))/5;
System.out.println(avg);
}
}
THANK YOU
Decision Making
Topic/Course
Sub-Topic (Example: name of college)
Decision/Selection statements

• if
• if else
• nested if
• if else if
• switch case
Simple if

• It is used to decide whether certain statement or block of statements


will be executed or not.
Syntax:

if (condition)
{
// Executes this block if condition is true
}
1 public class IfExample { output
2 public static void main(String[] args) {
3 int age=20;
4 if(age>18){ Age is greater than 18
5 System.out.print("Age is greater than 18");
6 }
7 }
8 }
if else

• It is used for two way decision making.


• If the condition is true then the if part is executed and if the condition
is false the else part will be executed.
Syntax:

if (condition)
{
// Executes this block if condition is true
}
else
{
// Executes this block if condition is false
}
1 class IfElseDemo output
2 {
3 public static void main(String args[])
4 {
5 int i = 10; i is smaller than 15
6 if (i < 15)
7 System.out.println("i is smaller than 15");
8 else
9 System.out.println("i is greater than 15");
10 }
11 }
Nested if
• An if else statement can contain any sort of statement within it.
• It can contain another if-else statement
• An if-else may be nested within the if part.
• An if-else may be nested within the else part.
• An if-else may be nested within both parts.
Syntax:

if (condition1)
{
// Executes when condition1 is true
if (condition2)
{
// Executes when condition2 is true
}
}
1 class NestedIfDemo output
2 {
3 public static void main(String args[])
4 {
5 int i = 10; i is smaller than 15
6 if (i == 10) i is smaller than 12 too
7 {
8 if (i < 15)
9 System.out.println("i is smaller than 15");
10 if (i < 12)
11 System.out.println("i is smaller than 12 too");
12 else
13 System.out.println("i is greater than 15");
14 }
15 }
16 }
if else if

• If else if statement is a multiway branch statement.


• In if-else-if statement, as soon as the condition is met, the
corresponding set of statements get executed, rest gets ignored.
Syntax:

if (condition1)
statement1;
else if (condition2)
statement2;
.
.
else
statement n;
1 class ifelseifDemo output
2 {
3 public static void main(String args[])
4 {
5 int i = 20;
6 i is 20
7 if (i == 10)
8 System.out.println("i is 10");
9 else if (i == 15)
10 System.out.println("i is 15");
11 else if (i == 20)
12 System.out.println("i is 20");
13 else
14 System.out.println("i is not present");
15 }
16 }
switch case

• The switch statement is a multiway branch statement.


• Expression can be of type byte, short, int char or an enumeration,
String.
• The break statement is optional. If omitted, execution will continue on
into the next case.
Syntax:

switch (expression)
{
case value1: statement1;
break;
case value2: statement2;
break;
.
.
case valueN: statementN;
break;
default: statementDefault;
}
1 class SwitchCaseDemo output
2 {
3 public static void main(String args[])
4 {
5 int i = 9;
6 switch (i) i is greater than 2.
7 {
8 case 0:
9 System.out.println("i is zero.");
10 break;
11 case 1:
12 System.out.println("i is one.");
13 break;
14 case 2:
15 System.out.println("i is two.");
16 break;
17 default:
18 System.out.println("i is greater than 2.");
19 }
20 }
21 }
1 // Predict the output
2 class Test {
3 public static void main(String[] args)
4 {
5 int x = 10;
6 if (x) {
7 System.out.println("HELLO");
8 } else {
9 System.out.println("BYE");
10 }
11 }
12 }
13
14
15
16
17
18
19
20
21
22
OUTPUT

1. HELLO
2. Compile time error
3. Runtime Error
4. BYE
1 // Predict the output
2 class Test {
3 public static void main(String[] args)
4 {
5 int x = 10;
6 if (x)
7 System.out.println("HELLO");
8 System.out.println("WELCOME");
9
10 else
11 {
12 System.out.println("BYE");
13 }
14 }
15 }
OUTPUT

1. HELLO WELCOME
2. HELLO
3. BYE
4. Compile time error
1 // Predict the output
2 class Test {
3 public static void main(String[] args)
4 {
5 if (true)
6 ;
7 }
8 }
OUTPUT

1. No Output
2. Compile time error
3. Runtime error
4. Runtime Exception
1 // Predict the output
2 class MainClass {
3 public static void main(String[] args)
4 {
5 int x = 10;
6 switch (x + 1 + 1) {
7 case 10:
8 System.out.println("HELLO");
9 break;
10 case 10 + 1 + 1:
11 System.out.println(“BYE");
12 break;
13 }
14 }
15 }
OUTPUT

1. Compile time error


2. BYE
3. HELLO
4. No Output
1 // Predict the output
2 public class A {
3 public static void main(String[] args)
4 {
5 if (true)
6 break;
7 }
8 }
OUTPUT

1. Nothing
2. Error
THANK YOU
Question 1
Write a program to get two integers n1 and n2 from the user and write a
program to relate 2 integers as equal to, less than or greater than..

Sample Input: Sample Output:


6 6 less than 8
8
1 import java.util.Scanner;
2 class Main
3 {
4 public static void main(String args[])
5 {
6 Scanner obj = new Scanner(System.in);
7 int n1 = obj.nextInt(); //n1-number 1
8 int n2 = obj.nextInt(); //n2-number 2
9 if(n1 == n2)
10 System.out.println(n1+" and "+n2+" are equal");
11 else
12 {
13 if(n1>n2)
14 System.out.println(n1+" greater than "+n2);
15 else
16 System.out.println(n1+" less than "+n2);
17 }
18 }
19 }
20
21
22
Question 2
Write a program to check whether the given character is vowel or consonant or Not an
alphabet.

Sample Input : Sample Output :

e Vowel
b Consonant
$ Not an alphabet
1 import java.util.Scanner;
2 class Main
3 {
4 public static void main(String args[])
5 {
6 Scanner obj = new Scanner(System.in);
7 char input = obj.next().charAt(0);
8 if(input >='a' && input <= 'z' || input >='A' && input <= 'Z')
9 {
10 if(input =='a'|| input =='e'||input=='i'||input=='o'||input=='u'||
11 input =='A'|| input =='E'||input=='I'||input=='O'||input=='U')
12 System.out.println("Vowel");
13 else
14 System.out.println("Consonant");
15 }
16 else
17 System.out.println("Not an alphabet");
18 }
19 }
20
21
22
Question 3
The newly appointed Vice-Chancellor of Anna University wanted to create an
automated grading system for the students to check their grade. When a student
enters a mark, the grading system displays the corresponding grade. Write a program
to solve the given problem. The grades for marks 100 - S, 90-99 is A, 80-89 is B, 70-79
is C, 60-69 is D, 50-59 is E and less than 50 is F.

Sample Input: Sample Output:


78 C
1 import java.util.Scanner;
2 class Main
3 {
4 public static void main(String args[])
5 {
6 Scanner obj = new Scanner(System.in);
7 int mark = obj.nextInt();
8 if(mark == 100)
9 System.out.println("S");
10 else if(mark>=90 && mark <=99)
11 System.out.println("A");
12 else if(mark>=80 && mark <=89)
13 System.out.println("B");
14 else if(mark>=70 && mark <=79)
15 System.out.println("C");
16 else if(mark>=60 && mark <=69)
17 System.out.println("D");
18 else if(mark>=50 && mark <=59)
19 System.out.println("E");
20 else
21 System.out.println("F");
22 }
Question 4
A fruit seller buys a dozen of banana at Rs.X. He sells 1 banana at Rs.Y. Write a
program to determine the profit or loss in Rs. for the fruitseller.

Sample Input: Sample Output:


60 Loss : Rs.12.00
4
1 import java.util.Scanner;
2 class Main
3 {
4 public static void main(String args[])
5 {
6 Scanner obj = new Scanner(System.in);
7 float total_cost = obj.nextFloat();//dozen of Banana total cost
8 float sold_cost = obj.nextFloat();//1 banana selling cost
9 float selling_price = 12*sold_cost;
10
11 if(total_cost > selling_price)
12 System.out.printf("Loss : Rs.%.2f",(total_cost-selling_price));
13
14 else if(total_cost < selling_price)
15 System.out.printf("profit : Rs.%.2f",(selling_price-total_cost));
16
17 else
18 System.out.println("No profit nor loss");
19 }
20 }
21
22
Question 5
Ask a user for their birth year encoded as two digits (like "62") and for the current
year, also encoded as two digits (like "99"). Write a program to find the users current
age in years.

Sample Input: Sample Output:


62 38
00
1 import java.util.Scanner;
2 class Main
3
{
4
5 public static void main(String args[])
6 {
7 Scanner obj = new Scanner(System.in);
8 int by = obj.nextInt();//by-Birth Year
9
int cy = obj.nextInt();//cy- Current Year
10
11 if(cy>by)
12 System.out.println(cy-by);
13 else
14 System.out.println(100-(by-cy));
15
}
16
17 }
18
19
20
21
22
Question 6
There are 3 labs in the CSE department are L1, L2, and L3 with a seating
capacity of x, y, and z. A single lab needs to be allocated to a class of 'n'
students. How many of the 3 labs can accommodate 'n' students?

Sample Input: Sample Output:


30 2
40
20
25
1 import java.util.Scanner;
2 class Main
3 {
4 public static void main(String args[])
5 {
6 Scanner obj = new Scanner(System.in);
7 int x = obj.nextInt();
8 int y = obj.nextInt();
9 int z = obj.nextInt();
10 int n = obj.nextInt();
11 int count = 0;
12 if(x>=n)
13 count++;
14 if(y>=n)
15 count++;
16 if(z>=n)
17 count++;
18 System.out.println(count);
19 }
20 }
21
22
Question 7
Dora is interested so much in gardening and she plants more trees in her garden. She
plants trees in a rectangular fashion with the order of rows and columns and
numbered the trees in row-wise order. She planted the mango tree only in a 1st row,
1st column and last column. So given the tree number, your task is to find whether the
given tree is a mango tree or not? Write a program to check whether the given number
is a mango tree or not.

Sample Input: Sample Output:


5 Yes
5
11
1 import java.util.Scanner;
2 class Main
3
{
4
5 public static void main(String args[])
6 {
7 Scanner s = new Scanner(System.in);
8 int rows = s.nextInt();
9
int columns = s.nextInt();
10
11 int tree_no = s.nextInt();
12 if((tree_no<=columns)||(tree_no%columns == 0)||
13 ((tree_no - 1)%columns==0))
14 System.out.println("Yes");
15
else
16
17 System.out.println("No");
18 }
19 }
20
21
22
Question 8
Write a program to calculate the hotel tariff. The room rent is 20% high during peak
seasons [April-June, November-December]. Note: Use the switch construct.

Sample Input: Sample Output:


3 3000.00
1500
2
1 import java.util.Scanner; 23 case 4:
2 class Main 24 case 5:
3 { 25 case 6:
public static void main(String args[]) 26 case 11:
4
{ 27 case 12:
5 Scanner s = new Scanner(System.in);
6 28
int month = s.nextInt(); System.out.printf("%.2f",(rent+(0.2*rent))
7 float rent = s.nextInt();
29 day);
8 int day = s.nextInt(); 30 break;
9 switch(month) 31 default:
10 { 32 System.out.println("Invalid Input");
11 case 1: 33 break;
12 case 2: 34 }
case 3: 35 }
13
case 7: 36 }
14 case 8:
15 case 9:
16 case 10:
17 System.out.printf("%.2f",rent*day);
18 break;
19
20
21
22
Question 9
A microwave oven manufacturer recommends that when heating two items, add
50% to the heating time, and when heating three items double the heating time.
Heating more than three items at once is not recommended. Write a program to find
out the recommended heating time.

Sample Input: Sample Output:


2 7.50
5.0
1 import java.util.Scanner;
2 class Main
3 {
public static void main(String args[])
4
{
5 Scanner s = new Scanner(System.in);
6 int item = s.nextInt();
7 float ht = s.nextFloat();//ht - heating time
8 switch(item){
9 case 1:
10 System.out.println(ht);
11 break;
12 case 2:
System.out.println((ht/2)+ht);
13
break;
14 case 3:
15 System.out.println(2*ht);
16 break;
17 default:
18 System.out.println("Number of items is more");
19 break;
20 }
21 }
}
22
Question 10
Ask the customer's age and for the time on a 24-hour clock (where noon
is 12.00 and 4:30 PM is 16.30). The show timings are 10.15, 13.30, 18.00
and 22.00. The normal adult ticket price is $8.00, however, the adult
matinee price is $5.00. Adults are those over 13 years. The normal
children's ticket price is $4.00, however, the children's matinee price is
$2.00. Write a program that determines the price of a movie ticket

Sample Input: Sample Output:


16 $8.00
10.15
1 import java.util.Scanner;
2 class Main
3 {
4 public static void main(String args[]){
5 Scanner s = new Scanner(System.in);
6 int age = s.nextInt();
7 float st = s.nextFloat();//st - Show timing
8 if(age > 13){
9 if(st >= 13.30 && st <= 17.59)//matinee show timing 13.30 to 17.59
10 System.out.println("$5.00");//evening show starts at 18.00
11 else
12 System.out.println("$8.00");
13 }
14 else
15 {
16 if(st >= 13.30 && st <= 17.59)//matinee show timing 13.30 to 17.59
17 System.out.println("$2.00");//evening show starts at 18.00
18 else
19 System.out.println("$4.00");
20 }
21 }
22 }
THANK YOU
Looping
Topic/Course
Sub-Topic (Example: name of college)
Looping

• A loop statement allows us to execute a statement or group of


statements multiple times.
Looping/Iteration statements

• for
• while
• do while
• Enhanced for
for

• It is used to iterate a part of the program several times.


• If the number of iteration is fixed, it is recommended to use for loop.
Syntax:

for (initialization condition; testing condition;


increment/decrement)
{
statement(s) ;
}
1 class forLoopDemo output
2 {
3 public static void main(String args[])
4 { Value of x:2
5 for (int x = 2; x <= 4; x++) Value of x:3
6 System.out.println("Value of x:" + x); Value of x:4
7 }
8 }
while

• It is used to iterate a part of the program several times.


• If the number of iteration is not fixed, it is recommended to use while
loop.
Syntax:

while(condition)
{
statement(s) ;
}
1 class whileLoopDemo output
2 {
3 public static void main(String args[])
4 {
5 int x = 1; Value of x:1
6 while (x <= 4) Value of x:2
7 { Value of x:3
8 System.out.println("Value of x:" + x); Value of x:4
9 x++;
10 }
11 }
12 }
do while
• It is used to iterate a part of the program several times.
• Use do while if the number of iteration is not fixed and you must have
to execute the loop at least once.
Syntax:

do
{

statement(s) ;

} while(condition);
1 class dowhileloopDemo output
2 {
3 public static void main(String args[])
4 {
5 int x = 21;
6 do
7 { Value of x: 21
8 System.out.println("Value of x:" + x);
9 x++;
10 }while (x < 20);
11 }
12 }
What is the difference between
while and do while ?
Enhanced for

• Enhanced for loop provides a simpler way to iterate through the


elements of a collection or array.
Syntax:

for (T element:Collection obj/array)


{
statement(s) ;
}
1 public class enhancedforloop output
2 {
3 public static void main(String args[])
4 { Ron
5 String array[] = {"Ron", "Harry","Hermoine"}; Harry
6 Hermoine
7 for (String x:array)
8 {
9 System.out.println(x);
10 }
11
12 }
13 }
When to use Enhanced for loop ?
Infinite loop

• One of the most common mistakes while implementing any sort of


looping is that it may not ever exit, that is the loop runs for infinite
time.
1 public class LooppitfallsDemo output
2 {
3 public static void main(String[] args)
4 {
5 int x = 5; In the loop
6 while (x == 5) In the loop
7 { In the loop
8 System.out.println("In the loop"); In the loop
9 } In the loop
10 } In the loop
11 } In the loop
In the loop
In the loop
In the loop
In the loop
..
..
..
Jump statements

• break
• continue
• return
break

• Used to break loop or switch statement.


• When a break statement is encountered inside a loop, the loop is
immediately terminated and the program control resumes at the next
statement following the loop.
1 public class BreakExample { output
2 public static void main(String[] args) {
3 for(int i=1;i<=10;i++){
4 if(i==5){ 1
5 break; 2
6 } 3
7 System.out.println(i); 4
8 }
9 }
10 }
continue

• Used to continue the loop, it continues the current flow of the program
and skips the remaining code at the specified condition.
• The continue statement is used in loop control structure when you
need to jump to the next iteration of the loop immediately.
• It can be used with for loop or while loop.
1 public class ContinueExample { output
2 public static void main(String[] args) {
3 for(int i=1;i<=10;i++){
4 if(i==5){ 1
5 continue; 2
6 } 3
7 System.out.println(i); 4
8 } 6
9 } 7
10 } 8
9
10
return

• Return is used to exit from a method, with or without a value.


1 // Predict the output
2 class Test {
3 public static void main(String[] args)
4 {
5 int j = 0;
6 do
7 for (int i = 0; i++ < 1 ; )
8 System.out.println(i);
9 while (j++ < 2);
10 }
11 }
OUTPUT

1. 111
2. 222
3. 333
4. error
1 // Predict the output
2 class Test {
3 static String s = "";
4 public static void main(String[] args)
5 {
6 P:
7 for (int i = 2; i < 7; i++) {
8 if (i == 3)
9 continue;
10 if (i == 5)
11 break P;
12 s = s + i;
13 }
14 System.out.println(s);
15 }
16 }
OUTPUT

1. 32
2. 23
3. 24
4. 42
1 // Predict the output
2 class Test {
3 public static void main(String[] args)
4 {
5 for (int i = 0; i < 10; i++)
6 int x = 10;
7 }
8 }
9
OUTPUT

1. No Output
2. Compile time error
3. Runtime error
4. Runtime Exception
1 // Predict the output
2 class Test {
3 public static void main(String[] args)
4 {
5 int i = 0;
6 for (System.out.println("HI"); i < 1; i++)
7 System.out.println("HELLO");
8 }
9 }
OUTPUT

1. HI HELLO
2. No Output
3. Compile time error
4. HELLO
1 // Predict the output
2 class Test {
3 public static void main(String[] args)
4 {
5 for (int i = 0;; i++)
6 System.out.println("HELLO");
7 }
8 }
OUTPUT

1. Compile time error


2. HELLO
3. HELLO(Infinitely)
4. Run-time Exception
THANK YOU
Looping
Topic/Course
Sub-Topic (Example: name of college)
Looping

• A loop statement allows us to execute a statement or group of


statements multiple times.
Looping/Iteration statements

• for
• while
• do while
• Enhanced for
for

• It is used to iterate a part of the program several times.


• If the number of iteration is fixed, it is recommended to use for loop.
Syntax:

for (initialization condition; testing condition;


increment/decrement)
{
statement(s) ;
}
1 class forLoopDemo output
2 {
3 public static void main(String args[])
4 { Value of x:2
5 for (int x = 2; x <= 4; x++) Value of x:3
6 System.out.println("Value of x:" + x); Value of x:4
7 }
8 }
while

• It is used to iterate a part of the program several times.


• If the number of iteration is not fixed, it is recommended to use while
loop.
Syntax:

while(condition)
{
statement(s) ;
}
1 class whileLoopDemo output
2 {
3 public static void main(String args[])
4 {
5 int x = 1; Value of x:1
6 while (x <= 4) Value of x:2
7 { Value of x:3
8 System.out.println("Value of x:" + x); Value of x:4
9 x++;
10 }
11 }
12 }
do while
• It is used to iterate a part of the program several times.
• Use do while if the number of iteration is not fixed and you must have
to execute the loop at least once.
Syntax:

do
{

statement(s) ;

} while(condition);
1 class dowhileloopDemo output
2 {
3 public static void main(String args[])
4 {
5 int x = 21;
6 do
7 { Value of x: 21
8 System.out.println("Value of x:" + x);
9 x++;
10 }while (x < 20);
11 }
12 }
What is the difference between
while and do while ?
Enhanced for

• Enhanced for loop provides a simpler way to iterate through the


elements of a collection or array.
Syntax:

for (T element:Collection obj/array)


{
statement(s) ;
}
1 public class enhancedforloop output
2 {
3 public static void main(String args[])
4 { Ron
5 String array[] = {"Ron", "Harry","Hermoine"}; Harry
6 Hermoine
7 for (String x:array)
8 {
9 System.out.println(x);
10 }
11
12 }
13 }
When to use Enhanced for loop ?
Infinite loop

• One of the most common mistakes while implementing any sort of


looping is that it may not ever exit, that is the loop runs for infinite
time.
1 public class LooppitfallsDemo output
2 {
3 public static void main(String[] args)
4 {
5 int x = 5; In the loop
6 while (x == 5) In the loop
7 { In the loop
8 System.out.println("In the loop"); In the loop
9 } In the loop
10 } In the loop
11 } In the loop
In the loop
In the loop
In the loop
In the loop
..
..
..
Jump statements

• break
• continue
• return
break

• Used to break loop or switch statement.


• When a break statement is encountered inside a loop, the loop is
immediately terminated and the program control resumes at the next
statement following the loop.
1 public class BreakExample { output
2 public static void main(String[] args) {
3 for(int i=1;i<=10;i++){
4 if(i==5){ 1
5 break; 2
6 } 3
7 System.out.println(i); 4
8 }
9 }
10 }
continue

• Used to continue the loop, it continues the current flow of the program
and skips the remaining code at the specified condition.
• The continue statement is used in loop control structure when you
need to jump to the next iteration of the loop immediately.
• It can be used with for loop or while loop.
1 public class ContinueExample { output
2 public static void main(String[] args) {
3 for(int i=1;i<=10;i++){
4 if(i==5){ 1
5 continue; 2
6 } 3
7 System.out.println(i); 4
8 } 6
9 } 7
10 } 8
9
10
return

• Return is used to exit from a method, with or without a value.


1 // Predict the output
2 class Test {
3 public static void main(String[] args)
4 {
5 int j = 0;
6 do
7 for (int i = 0; i++ < 1 ; )
8 System.out.println(i);
9 while (j++ < 2);
10 }
11 }
OUTPUT

1. 111
2. 222
3. 333
4. error
1 // Predict the output
2 class Test {
3 static String s = "";
4 public static void main(String[] args)
5 {
6 P:
7 for (int i = 2; i < 7; i++) {
8 if (i == 3)
9 continue;
10 if (i == 5)
11 break P;
12 s = s + i;
13 }
14 System.out.println(s);
15 }
16 }
OUTPUT

1. 32
2. 23
3. 24
4. 42
1 // Predict the output
2 class Test {
3 public static void main(String[] args)
4 {
5 for (int i = 0; i < 10; i++)
6 int x = 10;
7 }
8 }
9
OUTPUT

1. No Output
2. Compile time error
3. Runtime error
4. Runtime Exception
1 // Predict the output
2 class Test {
3 public static void main(String[] args)
4 {
5 int i = 0;
6 for (System.out.println("HI"); i < 1; i++)
7 System.out.println("HELLO");
8 }
9 }
OUTPUT

1. HI HELLO
2. No Output
3. Compile time error
4. HELLO
1 // Predict the output
2 class Test {
3 public static void main(String[] args)
4 {
5 for (int i = 0;; i++)
6 System.out.println("HELLO");
7 }
8 }
OUTPUT

1. Compile time error


2. HELLO
3. HELLO(Infinitely)
4. Run-time Exception
THANK YOU
Looping Program - Patterns
Topic/Course
Sub-Topic (Example: name of college)
Question 1
Write a program to generate the following patten.

Sample Input: Sample Output:


5 12345
2345
345
45
5
1 import java.util.Scanner;
2 class Pattern1
3 {
4 public static void main(String args[])
5 {
6 Scanner sc = new Scanner(System.in);
7 int n = sc.nextInt();
8 for(int i = 1; i<=n; i++)
9 {
10 int count = i;
11 for(int j = i; j<=n; j++)
12 {
13 System.out.print(count);
14 count++;
15 }
16 System.out.println();
17 }
18 }
19 }
20
21
22
Question 2
Write a program to generate the following patten.

Sample Input: Sample Output:


5 1
24
135
2468
13579
1 import java.util.Scanner;
2 class Pattern2
3 {
4 public static void main(String args[])
5 {
6 Scanner sc = new Scanner(System.in);
7 int n = sc.nextInt();
8 int k;
9 for(int i=1; i<=n; i++)
10 {
11 if(i % 2 == 1)
12 k = 1;
13 else
14 k = 2;
15 for(int j=1; j<=i; j++, k+=2)
16 {
17 System.out.print(k);
18 }
19 System.out.println();
20 }
21 }
22 }
Question 3
Write a program to generate the following patten.

Sample Input: Sample Output:


5 12345
23455
34555
45555
55555
1 import java.util.Scanner;
2 class Pattern3
3 {
4 public static void main(String args[])
5 {
6 Scanner sc = new Scanner(System.in);
7 int n = sc.nextInt();
8 for(int i = 1; i<=n; i++)
9 {
10 int count = i;
11 for(int j = 1; j<=n; j++)
12 {
13 System.out.print(count);
14 if(count <n)
15 count++;
16 }
17 System.out.println();
18 }
19 }
20 }
21
22
Question 4
Write a program to generate the following patten.

Sample Input: Sample Output:


5 12345
23451
34512
45123
51234
1 import java.util.Scanner;
2 class Pattern4
3 {
4 public static void main(String args[])
5 {
6 Scanner sc = new Scanner(System.in);
7 int n = sc.nextInt();
8 for(int i = 1; i<=n; i++)
9 {
10 int count = i;
11 for(int j = 1; j<=n; j++)
12 {
13 System.out.print(count);
14 count = count%n;
15 count++;
16 }
17 System.out.println();
18 }
19 }
20 }
21
22
Question 5
Write a program to generate the following patten.

Sample Input: Sample Output:


5 1
121
12321
1234321
123454321
1 import java.util.Scanner;
2 class Pattern6
3 {
4 public static void main(String args[])
5 {
6 Scanner sc = new Scanner(System.in);
7 int n = sc.nextInt();
8 for(int i=1; i<=n; i++){
9 for(int k = 1; k<=n-i ; k++) {
10 System.out.print(" ");
11 }
12 for(int j=1; j<=i; j++) {
13 System.out.print(j);
14 }
15 for(int j=i-1; j>=1; j--) {
16 System.out.print(j);
17 }
18 System.out.println();
19 }
20 }
21 }
22
Question 6
Write a program to generate the following patten.

Sample Input: Sample Output:


5 1
1 1
1 2 1
1 3 31
1 4 6 4 1
1 import java.util.Scanner;
2 class Pattern5
3 {
4 public static void main(String args[])
5 {
6 Scanner sc = new Scanner(System.in);
7 int n = sc.nextInt();
8 for(int line = 1; line <= n; line++) {
9 for(int space = 1; space<=n-line;space++){
10 System.out.print(" ");
11 }
12 int C=1;
13 for(int i = 1; i <= line; i++) {
14 System.out.print(C+" ");
15 C = C * (line - i) / i;
16 }
17 System.out.println();
18 }
19 }
20 }
21
22
THANK YOU
Control Structures
Topic/Course
Sub-Topic (Example: name of college)
Question 1
Write a program to generate the first n terms in the series
0.5,1.5,4.5,13.5,...

Input Format:
Input consists of a single integer which corresponds to n.

Output Format:
Output consists of the terms in the series separated by a blank space.

Sample Input: Sample Output:


5 0.5 1.5 4.5 13.5 40.5
Question 2
Write a program to generate the first n terms in the series
121,225,361,...

Input Format:
Input consists of a single integer which corresponds to n.

Output Format:
Output consists of the terms in the series separated by a blank space..

Sample Input: Sample Output:


4 121 225 361 529
Question 3
Write a program to generate the first n terms in the series.
0,2,8,14,...,34

Input Format:
Input consists of a single integer which corresponds to n.

Output Format:
Output consists of the terms in the series separated by a blank space..

Sample Input: Sample Output:


6 0 2 8 14 24 34
Question 4
Write a program to generate the first n terms in the series.
1,2.0,3.0,6.0,9.0,18.0,27.0,..

Input Format:
Input consists of a single integer which corresponds to n.

Output Format:
Output consists of the terms in the series separated by a blank space..

Sample Input: Sample Output:


8 1 2.0 3.0 6.0 9.0 18.0 27.0 54.0
Question 5
Write a program to generate the first n terms in the series.
4,5,9,18,34,...

Input Format:
Input consists of a single integer which corresponds to n.

Output Format:
Output consists of the terms in the series separated by a blank space.

Sample Input: Sample Output:


6 4 5 9 18 34 59
Question 6
Write a program to generate the given pattern.
CSK
CCSSKK
CCCSSSKKK
CCCCSSSSKKKK

Sample Input: Sample Output:


4 CSK
CCSSKK
CCCSSSKKK
CCCCSSSSKKKK
Question 7.1
The environmental eco club has discovered a new Amoeba that grows in
the order of a Fibonacci series every month. They are exhibiting their
amoeba in a national conference. They want to know the size of the
amoeba at a particular time instant. If a particular month’s index is given,
write a program to displays the amoeba’s size……???
For Example, The size of the amoeba on month 1, 2, 3, 4, 5, 6, ..will be 0,
1, 1, 2, 3, 5, 8 respectively.
Question 7.2
Input Format:
The first input containing an integer which denotes the number of the
month.

Output Format:
Print the amoeba size.
Refer the sample output for formatting.

Sample Input: Sample Output:


7 8
Question 8
a = 0, b=0, c=1 are the 1st three terms. All other terms in the Lucas
sequence are generated by
the sum of their 3 most recent predecessors.
Write a program to generate the first n terms of a Lucas Sequence.

Sample Input: Sample Output:


5 00112
Question 9
Write a program to check whether the given number is a trendy number
or not. A number is said to be a trendy number if and only if it has 3 digits
and the middle digit is divisible by 3.
Input Format:
The input containing an integer 'n' which denotes the given number

Output Format:
If the given number is a trendy number, then print "Trendy Number".
Otherwise, print "Not a Trendy Number".
Sample Input: Sample Output:
791 Trendy Number
Question 10.1
Write a program to that allows the user to enter 'n' numbers and finds the
number of positive numbers entered and the number of negative
numbers entered using a while loop.

Input Format:
Input consists of n+1 integers. The first integer corresponds to n. The next
n integers correspond to the numbers to be added. Consider 0 to be a
positive number.

Output Format:
Refer Sample Input and Output for formatting specifications.
Question 10.2
Sample Input: Sample Output:
Enter the values of n The number of positive number entered
4 is 2 and the sum is 11
5
-2
-1
6
How many times do you have to roll a pair of dice before they come up
snake eyes? You could do the experiment by rolling the dice by hand.
Write a computer program that simulates the experiment.
The program should report the number of rolls that it makes before the
dice come up snake eyes. (Note: "Snake eyes" means that both dice
show a value of 1.)
You can simulate rolling one die by choosing one of the integers 1, 2, 3,
4, 5, or 6 at random. The number you pick represents the number on the
die after it is rolled. The expression
(int)(Math.random()*6) + 1

does the computation you need to select a random integer between 1 and
6.
Which integer between 1 and 10000 has the largest number of divisors,
and how many divisors does it have? Write a program to find the
answers and print out the results. It is possible that several integers in
this range have the same, maximum number of divisors. Your program
only has to print out one of them

You might need some hints about how to find a maximum value. The
basic idea is to go through all the integers, keeping track of the largest
number of divisors that you've seen so far. Also, keep track of the
integer that had that number of divisors.
Write a program that will evaluate simple expressions such as 17 +
3 and 3.14159 * 4.7.
The expressions are to be typed in by the user. The input always
consist of a number, followed by an operator, followed by another
number.
The operators that are allowed are +, -, *, and /.
Your program should read an expression, print its value, read
another expression, print its value, and so on. The program should
end when the user enters 0 as the first number on the line.
Write a program that reads one line of input text and breaks it up into
words.
The words should be output one per line. A word is defined to be a
sequence of letters.
Any characters in the input that are not letters should be discarded. For
example, if the user inputs the line
He said, "That's not a good idea."
then the output of the program should be
He
Said
that
s
Not
a
good idea
Clue:
To test whether a character is a letter, you might use (ch >= 'a' && ch
<= 'z') || (ch >= 'A' && ch <= 'Z')
. However, this only works in English and similar languages. A better
choice is to call the standard function Character.isLetter(ch), which
returns a boolean value of true if ch is a letter and false if it is not.
This works for any Unicode character. For example, it counts an
accented e, é, as a letter.
THANK YOU
Java Inner Class

Class 1.1, 1.2, 1.3


Java Inner Classes - introduction
• Can we have another class as class
member?
• Yes, it is!
• Alternatively, it is called as NESTED
CLASSES
Java Inner Classes – syntax & example
class <class name> class STUDENT
{ {
member-1; int roll_no;
member-2; String name;
class <class name> class DATE
{ {
member-3; int dd,mm,yy;
… …
} }
} }
Java Inner Classes – instantiation
• To instantiate an inner class, we must first instantiate its enclosing
class
Outer outer = new Outer();
Outer.Inner inner = outer.new Inner();

• Example
STUDENT s1 = new STUDENT();
STUDENT.DATE dob = s1.new DATE();
1 class STUDENT
2 {
3 int roll_no=25;
4 String name="KUMAR";
5 class DATE
6 {
7 int dd=25,mm=12,yy=2000;
8 }
9 }
10 class ic1
11 {
12 public static void main(String[] args)
13 {
14 STUDENT s1 = new STUDENT();
15 STUDENT.DATE dob = s1.new DATE();
16
17 System.out.println("Roll Number : "+s1.roll_no);
18 System.out.println("Name : "+s1.name);
19 System.out.println("DoB : "+dob.dd+":"+dob.mm+":"+dob.yy);
20 }
21 }
22
OUTPUT

>javac ic1.java

>java ic1
Roll Number : 25
Name : KUMAR
DoB : 25:12:2000

>
OUTPUT

Class file details are:

For main class  ic1.class

For outer class  STUDENT.class

For inner class  STUDENT$DATE.class


Java Inner Classes - purpose
• logically group classes and interfaces
• readable and maintainable
• It can access all the members of outer class including private data
members and methods
• Code Optimization - requires less code to write
Java Inner Classes - merits
1) Nested classes are used to develop more readable and maintainable
code because it logically group classes and interfaces in one place only
2) Code Optimization - requires less code to write
Java Inner Classes – types (one way)
Java Inner Classes – types (alternate way)
Java Inner Classes - types
1. Member inner class - A class created within class and outside method
2. Anonymous inner class - A class created for implementing interface or
extending class
3. Local inner class - A class created within method
4. Static nested class - A static class created within class
5. Nested interface - An interface created within class or interface
Java Inner Classes - types
1. Member inner class
• A non-static class that is created inside a class but outside a method is
called member inner class
• Example
We are creating show_result() method in member inner class that is
accessing all the members of outer class including private member
1 class STUDENT
2 {
3 int roll_no=123;
4 String name="RAMU";
5 private String result="*PASS*";
6 class RESULT
7 {
8 void show_result()
9 {
10 System.out.println("Roll Number : "+roll_no);
11 System.out.println("Name : "+name);
12 System.out.println("Result :"+result);
13 } } }
14 class mic1
15 {
16 public static void main(String[] args)
17 {
18 STUDENT s1 = new STUDENT();
19 STUDENT.RESULT r1 = s1.new RESULT();
20 r1.show_result();
21 }
22 }
OUTPUT

>javac mic1.java

>java mic1
Roll Number : 123
Name : RAMU
Result :*PASS*

>
OUTPUT

Class file details are:

For main class  mic1.class

For outer class  STUDENT.class

For inner class  STUDENT$RESULT.class


Java Inner Classes – types
1. Member inner class – internal working
• The java compiler creates two class files in case of inner class
• The class file name of inner class is "Outer$Inner.class” ie.,
“STUDENT$RESULT.class”
• If we want to instantiate inner class, we must have to create the instance
of outer class
• In such case, instance of inner class is created inside the instance of
outer class
Java Inner Classes – types
1. Member inner class – internal working
• In this case, the java compiler creates a class file named
STUDENT$RESULT.class
• The Member inner class have the reference of Outer class that is why it
can access all the data members of Outer class including private
Java Inner Classes - types
2. Anonymous inner class
• It is an inner class without a name and for which only a
single object is created
• An anonymous inner class can be useful when making an
instance of an object with certain “extras” such as
overloading/overriding methods of a class or interface,
without having to actually subclass a class
Java Inner Classes - types
2. Anonymous inner class
• It can be created by two ways:
1. Class (may be abstract or concrete) or extending
2. Interface or implementing
1 abstract class STUDENT
2 {
3 abstract void cca(); // co-curricular activities
4 abstract void eca(); // extra-curricular activities
5 }
6
7 class aic1
8 {
9 public static void main(String args[])
10 {
11 STUDENT s1 = new STUDENT()
12 {
13 void cca()
14 {
15 System.out.println("My Co-curricular Activities:
16 Seminars & Conferences");
17 }
18 void eca()
19 {
20 System.out.println("My Extra-curricular Activities:
21 Cricket & Chess");
22 }
1
2 };
3 s1.cca();
4 s1.eca();
5 }
6 }
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
OUTPUT

>javac aic1.java

>java aic1
My Co-curricular Activities: Seminars & Conferences
My Extra-curricular Activities: Cricket & Chess

>
OUTPUT

Class file details are:

For abstract class  STUDENT.class

For main class  aic1.class

For anonymous inner class  aic1$1.class


Java Inner Classes - types
2. Anonymous inner class – extending a class (alternate)
• We know that we can create a thread by extending a
Thread class
• Suppose we need an immediate thread but we don’t
want to create a class that extend Thread class all the
time
Java Inner Classes - types
2. Anonymous inner class – extending a class (alternate)
• By the help of this type of Anonymous Inner class we can
define a ready thread as:
1
2 //Anonymous Inner class that extends a Class - Thread
3 class aic3
4 {
5 public static void main(String[] args)
6 {
7 Thread t1 = new Thread()
8 {
9 public void run()
10 {
11 System.out.println("Child Thread");
12 }
13 };
14 t1.start();
15 System.out.println("Main Thread");
16 }
17 }
18
19
20
21
22
OUTPUT

>javac aic3.java

>java aic3
Main Thread
Child Thread

>java aic3
Main Thread
Child Thread

>java aic3
Main Thread
Child Thread

>
OUTPUT

Class file details are:

For main class  aic3.class

For anonymous inner class  aic3$1.class


Java Inner Classes - types
2. Anonymous inner class – implementing an interface (alternate)
• We also know that by implementing Runnable interface
we can create a Thread
• Here we use anonymous Inner class that implements an
interface
1
2 //Anonymous Inner class that implements an interface - Thread
3 class aic4
4 {
5 public static void main(String[] args)
6 {
7 Runnable r1 = new Runnable()
8 {
9 public void run()
10 {
11 System.out.println("Child Thread");
12 }
13 };
14 Thread t1 = new Thread(r1);
15 t1.start();
16 System.out.println("Main Thread");
17 }
18 }
19
20
21
22
OUTPUT

>javac aic4.java

>java aic4
Main Thread
Child Thread

>java aic4
Main Thread
Child Thread

>java aic4
Main Thread
Child Thread

>
OUTPUT

Class file details are:

For main class  aic4.class

For anonymous inner class  aic4$1.class


Java Inner Classes - types
3. Local inner class
• A class created inside a method is called local inner class
• If we want to invoke the methods of local inner class, we
must instantiate this class inside the method
Java Inner Classes - types
3. Local inner class – class files
• When a program containing a local inner class is compiled, the
compiler generate two .class files,
• one for the outer class and
• the other for the inner class that has the reference to the outer class

• The two files are named by compiler as


• Outer.class
• Outer$1Inner.class
1 // local inner classes
2 class ARITHMETIC
3 {
4 private void getResult()
5 {
6 int a=5,b=3;
7 System.out.println("Inside inner class");
8 class CALCULATE
9 {
10 private int getSum()
11 {
12 return a+b;
13 }
14 private int getDiff()
15 {
16 return a-b;
17 }
18 private int getProduct()
19 {
20 return a*b;
21 }
22
1
2
3 private int getQuotient()
4 {
5 return a/b;
6 }
7 private int getReminder()
8 {
9 return a%b;
10 }
11 }
12 // inside method instantiating the class
13 CALCULATE calc = new CALCULATE();
14 System.out.println("a = "+a+"\tb = "+b);
15 System.out.println("Sum = "+ calc.getSum());
16 System.out.println("Difference = "+ calc.getDiff());
17 System.out.println("Product = "+ calc.getProduct());
18 System.out.println("Quotient = "+ calc.getQuotient());
19 System.out.println("Reminder = "+ calc.getReminder());
20
21 }
22
1
2
3 public static void main(String[] args)
4 {
5 ARITHMETIC arith = new ARITHMETIC();
6 arith.getResult();
7 }
8 }
9
10
11
12
13
14
15
16
17
18
19
20
21
22
OUTPUT

>javac arithmetic.java

>java ARITHMETIC
Inside inner class
a = 5 b = 3
Sum = 8
Difference = 2
Product = 15
Quotient = 1
Reminder = 2

>

Note:
Take care of case-sensitiveness of filename while execution
OUTPUT

Class file details are:

For outer class  ARITHMETIC.class

For local inner class  ARITHMETC$1CALCULATE.class


Java Inner Classes - types
3. Local inner class - rules
• Local inner class cannot be invoked from outside the
method
• Local variable can't be private, public or protected
• Local inner classes can extend an abstract class or can
also implement an interface
Java Inner Classes - types
3. Local inner class – rules…
• The scope of local inner class is restricted to the block
they are defined in
• A local class has access to the members of its enclosing
class
Java Inner Classes - types
4. Static nested class
• Nested classes that are declared static are called static
nested classes
• A static nested class in Java is simply a class scoped within
another class
• Static nested class as such shares no relationship with
enclosing class
Java Inner Classes - types
4. Static nested class
• It cannot access non-static data members and methods
• It can be accessed by outer class name
• It can access static data members of outer class including
private
• Static nested class cannot access non-static (instance) data
member or method
Java Inner Classes - types
4. Static nested class
• They are accessed using the enclosing class name
• A static nested class cannot refer directly to instance
variables or methods defined in its enclosing class,
• it can use them only through an object reference
Java Inner Classes - types
4. Static nested class
• OuterClass.StaticNestedClass
• Example
• To create an object for the static nested class, use this
syntax:
• OuterClass.StaticNestedClass nestedObject = new
OuterClass.StaticNestedClass();
1
2 // static nested class
3 class Outer
4 {
5 int outer_a = 100;
6 static int outer_b = 200;
7 private static int outer_c = 300;
8
9 static class Inner
10 {
11 void show()
12 {
13 // Error:can't access outer_a var
14 //System.out.println("outer_a = " + outer_a);
15 System.out.println("static outer_b = " + outer_b);
16 System.out.println("private static outer_c = " +
17 outer_c);
18 }
19 }
20 }
21
22
1
2
3
4 public class snc1
5 {
6 public static void main(String[] args)
7 {
8 Outer.Inner sncObj = new Outer.Inner();
9 sncObj.show();
10 }
11 }
12
13
14
15
16
17
18
19
20
21
22
OUTPUT

>javac snc1.java

>java snc1
static outer_b = 200
private static outer_c = 300

>
OUTPUT

Class file details are:

For main class  snc1.class

For outer class  Outer.class

For static inner class  Outer$Inner.class


1
2 // static nested class with static method
3 class Outer
4 {
5 int outer_a = 100;
6 static int outer_b = 200;
7 private static int outer_c = 300;
8
9 static class Inner
10 {
11 static void show()
12 {
13 System.out.println("Inside static method of static nested
14 class");
15 System.out.println("static outer_b = " + outer_b);
16 System.out.println("private static outer_c = " +
17 outer_c);
18 }
19 }
20 }
21
22
1
2
3
4 public class snc2
5 {
6 public static void main(String[] args)
7 {
8 Outer.Inner.show();
9 }
10 }
11
12
13
14
15
16
17
18
19
20
21
22
OUTPUT

>javac snc2.java

>java snc2
Inside static method of static nested class
static outer_b = 200
private static outer_c = 300

>
OUTPUT

Class file details are:

For main class  snc2.class

For outer class  Outer.class

For static inner class  Outer$Inner.class


Java Inner Classes - types
4. Static nested class Vs Non-static nested class
• Static nested classes do not directly have access to other
members ie., non-static variables and methods of the
enclosing class because as it is static, it must access the non-
static members of its enclosing class through an object
• That is, it cannot refer to non-static members of its enclosing
class directly
Java Inner Classes - types
4. Static nested class Vs Non-static nested class
• Non-static nested classes or inner classes has access to all
members ie.,static and non-static variables and methods,
(including private) of its outer class and may refer to them
directly in the same way that other non-static members of the
outer class do
Java Inner Classes - types
4. Static nested class - application
• A static nested class in Java serves a great advantage to
namespace resolution
• This is the basic idea behind introducing static nested classes
in Java
Java Inner Classes - types
5. Nested interface
• An interface which is declared inside another interface or class is
called nested interface
• They are also known as inner/member/nested interface
• Since nested interface cannot be accessed directly, the main
purpose of using them is to resolve the namespace by grouping
related interfaces (or related interface and class) together
Java Inner Classes - types
5. Nested interface
• Nested interfaces are static by default (java compiler internally creates
public and static interface)
• We don’t have to mark them static explicitly as it would be redundant
• Nested interfaces declared inside class can take any access modifier,
however nested interface declared inside interface is public implicitly
• We can only call the nested interface by using outer class or outer interface
name followed by dot( . ), followed by the interface name
1
2
3 // interface inside a class
4 class C1
5 {
6 interface I1
7 {
8 void display();
9 }
10 }
11
12 class C2 implements C1.I1
13 {
14 public void display()
15 {
16 System.out.println("display method of interface inside a
17 class");
18 }
19 }
20
21
22
1
2
3
4 class ni1
5 {
6 public static void main(String[] args)
7 {
8 C1.I1 obj1;
9 C2 obj2 = new C2();
10 obj1=obj2;
11 obj1.display();
12 }
13 }
14
15
16
17
18
19
20
21
22
OUTPUT

>javac ni1.java

>java ni1
display method of interface inside a class

>
OUTPUT

Class file details are:

For main class  ni1.class

For outer class  C1.class

For implementation class  C2.class


1
2
3 // nested interface
4 interface I1
5 {
6 interface I2
7 {
8 void display();
9 }
10 }
11
12 class C1 implements I1.I2
13 {
14 public void display()
15 {
16 System.out.println("nested interface: display method");
17 }
18 }
19
20
21
22
1
2
3
4 class ni2
5 {
6 public static void main(String[] args)
7 {
8 // normal way
9 I1.I2 obj1 ;
10 C1 obj2 = new C1();
11 obj1=obj2;
12 obj1.display();
13
14 //upcasting way
15 I1.I2 obj = new C1();
16 obj.display();
17 }
18 }
19
20
21
22
OUTPUT

>javac ni2.java

>java ni2
nested interface: display method
nested interface: display method

>
OUTPUT

Class file details are:

For main class  ni2.class

For outer interface  I1.class

For implementation class  C1.class


Java Inner Classes - types
5. Nested interface
• Can we define a class inside the interface?
• Yes, If we define a class inside the interface, java compiler creates a static
nested class
• Example:
interface A
{
class C { … }
}
Question 1

Which is true about a method-local inner class?

A) It must be marked final B) It can be marked abstract

C) It can be marked public D) It can be marked static


SOLUTION
because a method-local inner class can be abstract

Answer : B) It can be marked abstract


Question 2
which one create an anonymous inner class from within
class B?
(program is shown in next slide)

A) A a=new A(10) { }; B) A a=new B() { };

C) B b=new A(String s) { }; D) A a=new A.B(String s) { };


1
2
3 class A
4 {
5 A(String s) { }
6 A() { }
7 }
8
9
10 class B extends A
11 {
12 B() { }
13 B(String s) {super(s);}
14 void sample() { ... }
15 }
16
17
18
19
20
21
22
SOLUTION
A a=new B() { };

because anonymous inner classes are no different from


any other class when it comes to polymorphism

Answer : B) A a=new B() { };


Question 3

Which constructs an anonymous inner class instance?

A) Runnable r = new Runnable() { };


B) Runnable r = new Runnable(public void run() { });
C) Runnable r = new Runnable { public void run(){}};
D) System.out.println(new Runnable() {public void run() { }});
SOLUTION
System.out.println(new Runnable() {public void run() { }});

It defines an anonymous inner class instance, which also


means it creates an instance of that new anonymous
class at the same time

Answer : D)
Question 4

Which statement is true about a static nested class?

A) We must have a reference to an instance of the enclosing class in order


to instantiate it
B) It does not have access to non-static members of the enclosing class
C) It's variables and methods must be static
D) It must extend the enclosing class
SOLUTION
B) It does not have access to non-static members of the
enclosing class

because a static nested class is not tied to an instance of


the enclosing class, and thus can't access the non-static
members of the class

Answer : B)
Question 5
Which is true about an anonymous inner class?

A) It can extend exactly one class and implement exactly one interface
B) It can extend exactly one class and can implement multiple interfaces
C) It can extend exactly one class or implement exactly one interface
D) It can implement multiple interfaces regardless of whether it also
extends a class
SOLUTION
C) It can extend exactly one class or implement exactly
one interface

because the syntax of an anonymous inner class allows for only


one named type after the new, and that type must be either a
single interface or a single class

Answer : C)
Question 6
Which among the following best describes a nested class?

A) Class inside a class


B) Class inside a function
C) Class inside a package
D) Class inside a structure
SOLUTION
A) Class inside a class

If a class is defined inside another class, the inner class is


termed as nested class
The inner class is local to the enclosing class
Scope matters a lot here

Answer : A) Class inside a class


Question 7
Which feature of OOP reduces the use of nested classes?

A) Encapsulation
B) Inheritance
C) Binding
D) Abstraction
SOLUTION
B) Inheritance

Using inheritance we can have the security of the class being


inherited.
The subclass can access the members of parent class.
And have more feature than a nested class being used.

Answer : B) Inheritance
Question 8
Non-static nested classes have access to _________ from
enclosing class.

A) Private members
B) Protected members
C) Public members
D) All the members
SOLUTION
D) All the members

The non-static nested class can access all the members of the
enclosing class.
All the data members and member functions can be accessed
from the nested class.
Even if the members are private, they can be accessed.

Answer : D) All the members


Question 9
Which among the following is correct advantage/disadvantage of
nested classes?

A) Makes the code more complex


B) Makes the code unreadable
C) Makes the code efficient and readable
D) Makes the code multithreaded
SOLUTION
C) Makes the code efficient and readable

The use of nested classes make the code more streamed


towards a single concept.
This allows to group the most similar and related classes
together and makes it even more efficient and readable.

Answer : C) Makes the code efficient and readable


Question 10
How to create object of the inner class?

A) OuterClass.InnerClass innerObject = outerObject.new InnerClass();


B) OuterClass.InnerClass innerObject = new InnerClass();
C) InnerClass innerObject = outerObject.new InnerClass();
D) OuterClass.InnerClass = outerObject.new InnerClass();
SOLUTION
A) OuterClass.InnerClass innerObject = outerObject.new
InnerClass();

An instance of inner class can exist only within instance of outer


class.
To instantiate the inner class, one must instantiate the outer
class first.
This can be done by the correct syntax above.

Answer : A)
Question 11
A static nested class is _____________ class in behavior that is
nested in another _________ class.

A) Top level, top level


B) Top level, low level
C) Low level, top level
D) Low level, low level
SOLUTION
A) Top level, top level

Top level class encloses the other classes or have same


preference as that of other top level classes.
Having a class inside the top level class is indirectly having a top
level class which higher degree of encapsulation.

Answer : A) Top level, top level


Question 12
If a declaration of a member in inner class has the same name as
that in the outer class, then ___________ enclosing scope.

A) Outer declaration shadows inner declaration in


B) Inner declaration shadows outer declaration in
C) Declaration gives compile time error
D) Declaration gives runtime error
SOLUTION
B) Inner declaration shadows outer declaration in

The inner class will have more preference for its local members
than those of the enclosing members.
Hence it will shadow the enclosing class members.
This process is known as shadowing.

Answer : B)
Question 13
Instance of inner class can exist only _______________
enclosing class.

A) Within
B) Outside
C) Private to
D) Public to
SOLUTION
A) Within

The class defined inside another class is local to the enclosing


class.
This means that the instance of inner class will not be valid
outside the enclosing class.
There is no restriction for instance to be private or public always.

Answer : A) Within
Question 14
A nested class can have its own static members.

A) True B) False
SOLUTION
B) False

The nested classes are associated with the object of the


enclosing class.
Hence have direct access to the members of that object.
Hence the inner class can’t have any static members of its own.
Otherwise the rule of static members would be violated using
enclosing class instance.

Answer : B) False
Question 15
How to access static nested classes?

A) OuterClass.StaticNestedClass
B) OuterClass->StaticNestedClass
C) OuterClass(StaticNestedClass)
D) OuterClass[StaticNestedClass]
SOLUTION
A) OuterClass.StaticNestedClass

Like any other member of the class, the static nested class uses
the dot operator to be accessed.
The reason behind is, the static classes can’t work with
instances, hence we use enclosing class name to access static
nested class.

Answer : A) OuterClass.StaticNestedClass
Question 16
What is the output of the following java program?

A) 15 B) 9

C) 5 D) Compilation Error
1 public class Outer
2 {
3 public static int temp1 = 1;
4 private static int temp2 = 2;
5 public int temp3 = 3;
6 private int temp4 = 4;
7 public static class Inner
8 {
9 private static int temp5 = 5;
10
11 private static int getSum()
12 {
13 return (temp1 + temp2 + temp3 + temp4 + temp5);
14 }
15 }
16 public static void main(String[] args)
17 {
18 Outer.Inner obj = new Outer.Inner();
19 System.out.println(obj.getSum());
20 }
21
22 }
SOLUTION
D) Compilation Error

static inner classes cannot access non-static fields of the


outer class

Answer : D) Compilation Error


Question 17
What is the output of the following java program?

A) Compilation Error B) Runtime Error

C) 200 D) None of the above


1 public class Outer
2 {
3 private static int data = 10;
4 private static int LocalClass()
5 {
6 class Inner
7 {
8 public int data = 20;
9 private int getData()
10 {
11 return data;
12 }
13 };
14 Inner inner = new Inner();
15 return inner.getData();
16 }
17 public static void main(String[] args)
18 {
19 System.out.println(data * LocalClass());
20 }
21 }
22
SOLUTION
C) 200

LocalClass() method defines a local inner class.


This method creates an object of class Inner and return the value of
the variable data that resides within it.

Answer : C) 200
Question 18
What is the output of the following java program?

A) Compilation Error B) Runtime Error

C) 25 D) 20
1
2 interface Anonymous
3 {
4 public int getValue();
5 }
6 public class Outer
7 {
8 private int data = 15;
9 public static void main(String[] args)
10 {
11 Anonymous inner = new Anonymous()
12 {
13 int data = 5;
14 public int getValue() { return data; }
15 public int getData() { return data; }
16 };
17 Outer outer = new Outer();
18 System.out.println(inner.getValue() + inner.getData() +
19 outer.data);
20 }
21 }
22
SOLUTION
A) Compilation Error

The method getData() is undefined in Anonymous class which


causes the compilation error.

Answer : A) Compilation Error


Question 19
What is the output of the following java program?

A) Compilation Error B) 2010

C) 1020 D) None
1
2 public class Outer {
3 private int data = 10;
4 class Inner {
5 private int data = 20;
6 private int getData() { return data; }
7 public void main(String[] args)
8 {
9 Inner inner = new Inner();
10 System.out.println(inner.getData());
11
12 }
13 }
14 private int getData() { return data; }
15 public static void main(String[] args)
16 {
17 Outer outer = new Outer();
18 Outer.Inner inner = outer.new Inner();
19 System.out.printf("%d", outer.getData());
20 inner.main(args);
21 }
22 }
SOLUTION
A) Compilation Error

Inner class defined above though, have access to the private


variable data of the Outer class, but declaring a variable data inside
an inner class makes it specific to the Inner class with no conflicts in
term of variable declaration

Answer : A) Compilation Error


Question 20
What is the output of the following java program?

A) Compilation Error B) Runtime Error

C) 100 D) None
1
2 interface OuterInterface
3 {
4 public void InnerMethod();
5 public interface InnerInterface
6 {
7 public void InnerMethod();
8 }
9 }
10 public class Outer implements OuterInterface.InnerInterface, OuterInterface
11 {
12 public void InnerMethod()
13 {
14 System.out.println(100);
15 }
16 public static void main(String[] args)
17 {
18 Outer obj = new Outer();
19 obj.InnerMethod();
20 }
21 }
22
SOLUTION
C) 100

As both the interfaces has declaration of InnerMethod(),


implementing it once works for both the InnerInterface and
OuterInterface.

Answer : C) 100
THANK YOU

You might also like