Java Programmes
Java Programmes
Java Programmes
System.out.println(“Hello World”);
Literals in Java
package com.company;
char ch = 'A';
float f1 = 5.6f;
double d1 = 4.66;
boolean a = true;
System.out.print(age);
System.out.println(str);
}
import java.util.Scanner;
// int a = sc.nextInt();
// float a = sc.nextFloat();
// int b = sc.nextInt();
// float b = sc.nextFloat();
// System.out.println(sum);
// boolean b1 = sc.hasNextInt();
// System.out.println(b1);
// String str = sc.next();
System.out.println(str);
package com.company;
import java.util.Scanner;
// Question1
// int a = 4;
// int b = 17;
// int c =6;
// System.out.println(sum);
// Question2
// System.out.println(cgpa);
// Question 3
// Question 5
System.out.println(sc.hasNextInt());
Precedence of operators
package com.company;
// 1. Arithmetic Operators
int a = 4;
int b = 9;
b *= 3;
System.out.println(b);
// 3. Comparison Operators
// System.out.println(64<6);
// 4. Logical Operators
System.out.println(64>5 || 64>98);
// 5. Bitwise Operators
System.out.println(2&3);
// 10
// 11
// ----
// 10
Associativity of Operators
package com.company;
public class cwh_09_ch2_op_pre {
//int a = 6*5-34/2;
/*
=30-34/2
=30-17
=13
*/
//int b = 60/5-34*2;
/*
= 12-34*2
=12-68
=-56
*/
//System.out.println(a);
//System.out.println(b);
// Quick Quiz
int x =6;
int y = 1;
// int k = x * y/2;
int b = 0;
int c = 0;
int a = 10;
System.out.println(k);
}
increment and decrement
package com.company;
int y = 6;
short z = 8;
int a = y + z;
float b = 6.54f + x;
System.out.println(b); */
int i = 56;
int j = 67;
System.out.println(i++);
System.out.println(i);
System.out.println(++i);
System.out.println(i);
int y = 7;
char ch = 'a';
System.out.println(++ch);
}
}
Write a program to calculate the percentage of a given student in the CBSE board exam. His
marks from 5 subjects must be taken as input from the keyboard. (Marks are out of 100)
package com.company;
import java.util.Scanner;
System.out.println("percentage : ");
System.out.println(percentage);
}
1. What will be the result of the following expression:
1. Write a java program to encrypt a grade by adding 8 to it. Decrypt it to show the correct
grade.
2. Use comparison operators to find out whether a given number is greater than the user
entered number or not.
3. Write the following expression in a java program:
v2-u2/2as
int x = 7
Value of a?
package com.company;
System.out.println(a);
2ANS:
package com.company;
System.out.println(grade);
System.out.println(grade);
}
3ANS
package com.company;
import java.util.Scanner;
int a = sc.nextInt();
System.out.println(a>8);
System.out.println(7*49/7+35/7);
Strings
package com.company;
import java.util.Scanner;
// System.out.print(name);
int a = 6;
float b = 5.6454f;
// String st = sc.next();
// String st = sc.nextLine();
// System.out.println(st);
String Methods
package com.company;
// System.out.println(name);
//System.out.println(lstring);
//System.out.println(ustring);
//System.out.println(nonTrimmedString);
//System.out.println(trimmedString);
//System.out.println(name.substring(1));
//System.out.println(name.substring(1,5));
//System.out.println(name.replace('r', 'p'));
//System.out.println(name.replace("r", "ier"));
//System.out.println(name.startsWith("Har"));
//System.out.println(name.endsWith("dd"));
//System.out.println(name.charAt(4));
//System.out.println(modifiedName.indexOf("rry"));
//System.out.println(modifiedName.indexOf("rry", 4));
//System.out.println(modifiedName.lastIndexOf("rry", 7));
//System.out.println(name.equals("Harry"));
System.out.println(name.equalsIgnoreCase("HarRY"));
}
1. Write a Java program to convert a string to lowercase.
2. Write a Java program to replace spaces with underscores.
3. Write a Java program to fill in a letter template which looks like below:
package com.company;
// Problem 1
//name = name.toLowerCase();
//System.out.println(name);
// Problem 2
//System.out.println(text);
// Problem 3
String letter = "Dear <|name|>, Thanks a lot!";
System.out.println(letter);
// Problem 4
System.out.println(myString.indexOf(" "));
System.out.println(myString.indexOf(" "));
// Problem 5
System.out.println(myLetter);
If-Else Statement
/* if (condition-to-be-checked) {
statements-if-condition-true;
else {
statements-if-condition-false;
} */
else-if clause
/* if (condition1) {
//Statements;
else if {
// Statements;
else {
//Statements
} */
boolean a = true;
boolean b = false;
// if (a && b){
// System.out.println("Y");
// }
// else{
// System.out.println("N");
// }
// if (a || b){
// System.out.println("Y");
// }
// else{
// System.out.println("N");
// }
System.out.print("Not(a) is ");
System.out.println(!a);
System.out.print("Not(b) is ");
System.out.println(!b);
Case C1:
//Code;
break;
Case C2:
//Code;
break;
Case C3:
//Code
break;
default:
//Code
} */
import java.util.Scanner;
switch (var) {
/*
int age;
age = sc.nextInt();
if (age>56){
else if(age>46){
else if(age>36){
else{
if(age>2){
*/
int a = 10;
if (a=11)
System.out.println(“I am 11”);
else
System.out.println(“I am not 11”);
Copy
2. Write a program to find out whether a student is pass or fail; if it requires total 40% and at least
33% in each subject to pass. Assume 3 subjects and take marks as an input from the user.
3. Calculate income tax paid by an employee to the government as per the slabs mentioned below:
Income
Tax
Slab
2.5L –
5%
5.0L
5.0L –
20%
10.0L
Above
30%
10.0L
Note that there is not tax below 2.5L. Take the input amount as input from the user.
4. Write a Java program to find out the day of the week given the number [1 for Monday, 2 for
Tuesday … and so on!]
5. Write a Java program to find whether a year entered by the user is a leap year or not.
6. Write a program to find out the type of website from the URL:
package com.company;
import java.util.Scanner;
import java.util.Random;
public class cwh_19_ch4_ps {
// Question 1:
// int a = 11;
// if(a=11){
//
// }
// Question 2
// m1 = sc.nextByte();
//
// m2= sc.nextByte();
//
// m3 = sc.nextByte();
// }
// else{
// System.out.println("Sorry, You have not been promoted! Please try again.");
// }
// Question 3
// float tax = 0;
// if(income<=2.5){
// tax = tax + 0;
// }
// }
// }
// else if(income>10.0f){
// }
//
//
// switch (day){
// }
// Question 6
// if(website.endsWith(".org")){
// }
// else if(website.endsWith(".com")){
// }
// else if(website.endsWith(".in")){
// }
int a = r.nextInt();
System.out.println(a);
While loops
/*
*/
package com.company;
System.out.println(1);
System.out.println(2);
System.out.println(3);
System.out.println("Using Loops:");
int i = 100;
while(i<=200){
System.out.println(i);
i++;
// while(true){
// }
do-while loop:
/* do {
//code
package com.company;
// while(a<5){
// System.out.println(a);
// a++;
// }
int b = 10;
do {
System.out.println(b);
b++;
}while(b<5);
int c = 1;
do{
System.out.println(c);
c++;
}while(c<=45);
For loop:
//code;
} */
Decrementing for loop
for (i=7; i!=0; i--){
System.out.println(i);
package com.company;
// System.out.println(i);
// }
// 2i = Even Numbers = 0, 2, 4, 6, 8
//int n = 3;
// System.out.println(2*i+1);
//}
System.out.println(i);
}
break and continue in Java
package com.company;
// System.out.println(i);
// System.out.println("Java is great");
// if(i==2){
// break;
// }
// }
// int i=0;
// do{
// System.out.println(i);
// System.out.println("Java is great");
// if(i==2){
// }
// i++;
// }while(i<5);
// for(int i=0;i<50;i++){
// if(i==2){
// continue;
// }
// System.out.println(i);
// System.out.println("Java is great");
// }
int i=0;
do{
i++;
if(i==2){
System.out.println(i);
System.out.println("Java is great");
}while(i<5);
}
Write a program to print the following pattern
****
***
**
At most once
Repeat problem 2 using for loop.
package com.company;
// Practice Problem 1
// int n = 4;
// for(int j=0;j<i;j++){
// System.out.print("*");
// }
// System.out.print("\n");
// }
// Practice Problem 2
// int sum=0;
// int n=4;
// for(int i=0;i<n;i++){
// }
// System.out.println(sum);
// Practice Problem 3
// int n = 5;
// for(int i=1;i<=10;i++){
// }
// Practice Problem 4
// int n = 10;
// for(int i=10;i>=1;i--){
// }
// Practice Problem 6
// int n = 5;
// // 5! = 5*4*3*2*1 = 120
// int i = 1;
// int factorial = 1;
// while(i<=n){
// factorial *= i;
// i++;
// }
// System.out.println(factorial);
// Practice Problem 9
// int n = 8;
// int sum = 0;
// for(int i=1;i<=10;i++){
// sum += n*i;
// }
// System.out.println(sum);
Displaying an Array
Code as Described
package com.company;
/* Classroom of 500 students - You have to store marks of these 500 students
*/
// int [] marks;
// Initialization
// marks[0] = 100;
// marks[1] = 60;
// marks[2] = 70;
// marks[3] = 90;
// marks[4] = 86;
System.out.println(marks[4]);
} */
/*
System.out.println(students.length);
System.out.println(students[2]);
*/
// System.out.println(marks.length);
System.out.println(marks[0]);
System.out.println(marks[1]);
System.out.println(marks[2]);
System.out.println(marks[3]);
System.out.println(marks[4]);
// Displaying the Array (for loop)
for(int i=0;i<marks.length;i++){
System.out.println(marks[i]);
System.out.println(marks[i]);
System.out.println(element);
flats[0][0] = 100
flats[0][1] = 101
flats[0][2] = 102
// … & so on!
3-D array
CODE
package com.company;
flats[0][0] = 101;
flats[0][1] = 102;
flats[0][2] = 103;
flats[1][0] = 201;
flats[1][1] = 202;
flats[1][2] = 203;
for(int i=0;i<flats.length;i++){
for(int j=0;j<flats[i].length;j++) {
System.out.print(flats[i][j]);
System.out.print(" ");
}
System.out.println("");
Code Solution:
package com.company;
// Practice Problem 1
float sum = 0;
for(float element:marks){
// Practice Problem 2
for(float element:marks){
if(num==element){
isInArray = true;
break;
if(isInArray){
else{
// Practice Problem 3
float sum = 0;
for(float element:marks){
// Practice Problem 4
int [][] mat1 = {{1, 2, 3},
{4, 5, 6}};
{3, 7, 1}};
{0, 0, 0}};
// Practice Problem 5
int l = arr.length;
int n = Math.floorDiv(l, 2);
int temp;
// a b temp
// |4| |3| ||
temp = arr[i];
arr[i] = arr[l-i-1];
arr[l-i-1] = temp;
// Practice Problem 6
for(int e: arr){
if(e>max){
max = e;
System.out.println("the value of the maximum element in this array is: "+ max);
// Practice Problem 6
System.out.println(Integer.MIN_VALUE);
System.out.println(Integer.MAX_VALUE);
*/
// Practice Problem 7
for(int i=0;i<arr.length-1;i++){
isSorted = false;
break;
if(isSorted){
else{
Methods in Java
Syntax of a Method
dataType name() {
//Method body
int c = a+b;
Source code
package com.company;
int z;
if(x>y){
z = x+y;
else {
z = (x +y) * 5;
x = 566;
return z;
int b = 7;
int c;
c = logic(a, b);
int a1 = 2;
int b1 = 1;
int c1;
c1 = logic(a1, b1);
System.out.println(c);
System.out.println(c1);
Overloading in Java
package com.company;
}
static void foo(int a){
a = 98;
arr[0] = 98;
"Plagiarism!");
}
public static void main(String[] args) {
// tellJoke();
//int x = 45;
//change(x);
// change2(marks);
// Method Overloading
foo();
foo(3000);
foo(3000, 4000);
// factorial(0) = 1
// factorial(5) = 5 * 4 * 3 * 2 * 1 = 120
// factorial(n) = n * factorial(n-1)
if(n==0 || n==1){
return 1;
else{
return n * factorial(n-1);
if(n==0 || n==1){
return 1;
else{
int product = 1;
product *= i;
}
return product;
int x = 0;
*
**
***
****
****
***
**
*
Code Solution:
package com.company;
System.out.print("*");
System.out.println();
if (n > 0) {
pattern1_rec(n - 1);
System.out.println();
// pattern1_rec(3)
// pattern1_rec(1) + 2 times star and new line + 3 times star and new line
// pattern1_rec(0) + 1 times star and new line + 2 times star and new line + 3 times star and new line
// sum(n) = 1 + 2 + 3... + n
// sum(n) = sum(n-1) + n
// sum(3) = 3 + sum(2)
// sum(3) = 3 + 2 + sum(1)
// sum(3) = 3 + 2 + 1
// Base condition
if (n == 1) {
return 1;
}
static int fib(int n) {
/* if(n==1){
return 0;
else if(n==2){
return 1;
} */
if (n == 1 || n == 2) {
return n - 1;
} else {
// Problem 1
// multiplication(7);
// Problem 2
// pattern1(9);
// Problem 3
// int c = sumRec(4);
// System.out.println(c);
// Problem 4
// System.out.println(result);
// Problem 8
pattern1(9);
//code
};
*/
class Employee{
int id;
int salary;
String name;
return salary;
harry.id = 12;
harry.salary = 34;
harry.name = "CodeWithHarry";
john.id = 17;
john.salary = 12;
harry.printDetails();
john.printDetails();
System.out.println(salary);
// System.out.println(harry.id);
// System.out.println(harry.name);
class Employee{
int salary;
String name;
return salary;
return name;
name = n;
class CellPhone{
System.out.println("Vibrating...");
System.out.println("Calling Mukul...");
class Square{
int side;
return side*side;
return 4*side;
class Tommy{
}
public void run(){
/*
// Problem 1
harry.setName("CodeWithHarry");
harry.salary = 233;
System.out.println(harry.getSalary());
System.out.println(harry.getName());
// Problem 2
asus.callFriend();
asus.vibrate();
//asus.ring();
// Problem 3
Square sq = new Square();
sq.side = 3;
System.out.println(sq.area());
System.out.println(sq.perimeter());
*/
// Problem 5
player1.fire();
player1.run();
player1.hit();
package com.company;
class MyEmployee{
return name;
}
public void setName(String n){
this.name = n;
this.id = i;
return id;
// harry.id = 45;
harry.setName("CodeWithHarry");
System.out.println(harry.getName());
harry.setId(234);
System.out.println(harry.getId());
Exercise 2
package com.company;
import java.util.Random;
import java.util.Scanner;
// 0 for Rock
// 1 for Paper
// 2 for Scissor
if (userInput == computerInput) {
System.out.println("Draw");
System.out.println("You Win!");
} else {
System.out.println("Computer Win!");
else if(computerInput==1){
else if(computerInput==2){
Constructors in Java
package com.company;
class MyMainEmployee{
public MyMainEmployee(){
id = 0;
name = "Your-Name-Here";
id = myId;
name = myName;
}
id = 1;
name = myName;
return name;
this.name = n;
this.id = i;
return id;
//harry.setName("CodeWithHarry");
//harry.setId(34);
System.out.println(harry.getId());
System.out.println(harry.getName());
1. create a class cylinder and use getter and setters to set its radius and
height
2. use ➊ to calculate surface and volume of the cylinder
3. Use a constructor and repeat ➊
4. Overload a constructor used to initialize a rectangle of length and
breath 5 for using custom parameters
5. Repeat ➊ for a sphere
class Cylinder{
this.radius = radius;
this.height = height;
return radius;
}
public void setRadius(int radius) {
this.radius = radius;
return height;
this.height = height;
class Rectangle{
this.length = 4;
this.breadth = 5;
this.length = length;
this.breadth = breadth;
return length;
return breadth;
/*
// Problem 1
System.out.println(myCylinder.getHeight());
//myCylinder.setRadius(9);
System.out.println(myCylinder.getRadius());
// Problem 2
System.out.println(myCylinder.surfaceArea());
System.out.println(myCylinder.volume());
*/
// Problem 3
System.out.println(r.getLength());
System.out.println(r.getBreadth());
Inheritance in Java
package com.company;
class Base{
public int x;
return x;
}
public void setX(int x) {
this.x = x;
System.out.println("I am a constructor");
public int y;
return y;
this.y = y;
b.setX(4);
System.out.println(b.getX());
d.setY(43);
System.out.println(d.getY());
package com.company;
class Base1{
Base1(){
System.out.println("I am a constructor");
Base1(int x){
Derived1(){
//super(0);
super(x);
ChildOfDerived(){
super(x, y);
package com.company;
import javax.print.Doc;
class EkClass{
int a;
return a;
EkClass(int a){
this.a = a;
return 1;
DoClass(int c){
super(c);
System.out.println("I am a constructor");
}
System.out.println(e.getA());
this keyword
this is a way for us to reference an object of the class which is being
created / referenced.
Super keyword
A reference variable used to refer immediate parent class object
package com.company;
class A{
public int a;
return 4;
}
public void meth2(){
class B extends A{
@Override
A a = new A();
a.meth2();
B b = new B();
b.meth2();
package com.company;
class Phone{
System.out.println("Time is 8 am");
System.out.println("Turning on Phone...");
System.out.println("Playing music...");
System.out.println("Turning on SmartPhone...");
// obj.name();
obj.showTime();
obj.on();
Create a class Game, which allows a user to play "Guess the Number"
game once.
package com.company;
import java.util.Random;
import java.util.Scanner;
class Game{
return noOfGuesses;
this.noOfGuesses = noOfGuesses;
Game(){
this.number = rand.nextInt(100);
}
void takeUserInput(){
inputNumber = sc.nextInt();
boolean isCorrectNumber(){
noOfGuesses++;
if (inputNumber==number){
return true;
else if(inputNumber<number){
System.out.println("Too low...");
else if(inputNumber>number){
System.out.println("Too high...");
return false;
}
}
/*
*/
boolean b= false;
while(!b){
g.takeUserInput();
b = g.isCorrectNumber();
}
}
package com.company;
//
package com.company;
class Circle{
Circle(){
Circle(int r){
this.radius = r;
return Math.PI*this.radius*this.radius;
}
}
super(r);
this.height = h;
return Math.PI*this.radius*this.radius*this.height;
// Problem 1
}
Abstract Class & Abstract Methods
package com.company;
public Parent2(){
System.out.println("Hello");
@Override
System.out.println("Good morning");
@Override
public void greet2(){
System.out.println("Good afternoon");
System.out.println("I am good");
Interfaces in java
interface Bicycle {
int speed = 7 ;
CODE :
package com.company;
interface Bicycle{
int a = 45;
}
interface HornBicycle{
int x = 45;
void blowHornK3g();
void blowHornmhn();
//public int x = 5;
void blowHorn(){
System.out.println("Applying Brake");
System.out.println("Applying SpeedUP");
}
public void blowHornmhn(){
cycleHarry.applyBrake(1);
System.out.println(cycleHarry.a);
System.out.println(cycleHarry.x);
// cycleHarry.a = 454;
//System.out.println(cycleHarry.a);
cycleHarry.blowHornK3g();
cycleHarry.blowHornmhn();
}
Java Interfaces Example & Default Methods
Default method
package com.company;
interface MyCamera{
void takeSnap();
void recordVideo();
System.out.println("Good Morning");
greet();
System.out.println("Recording in 4k...");
interface MyWifi{
String[] getNetworks();
class MyCellPhone{
void pickCall(){
System.out.println("Connecting... ");
System.out.println("Taking snap");
System.out.println("Taking snap");
// }
return networkList;
ms.record4KVideo();
String[] ar = ms.getNetworks();
System.out.println(item);
Inheritance in Interfaces :
void meth 2( );
package com.company;
interface sampleInterface{
void meth1();
void meth2();
void meth3();
void meth4();
System.out.println("meth1");
System.out.println("meth2");
System.out.println("meth3");
System.out.println("meth4");
}
}
obj.meth1();
obj.meth2();
obj.meth3();
Polymorphism in Interfaces
package com.company;
interface MyCamera2{
void takeSnap();
void recordVideo();
System.out.println("Good Morning");
greet();
System.out.println("Recording in 4k...");
interface MyWifi2{
String[] getNetworks();
class MyCellPhone2{
void pickCall(){
System.out.println("Connecting... ");
System.out.println("Taking snap");
System.out.println("Taking snap");
// }
return networkList;
System.out.println("meth");
}
}
cam1.record4KVideo();
s.sampleMeth();
s.recordVideo();
s.getNetworks();
s.callNumber(7979);
package com.company;
void write(){
System.out.println("Write");
void refill(){
System.out.println("Refill");
void changeNib(){
class Monkey{
void jump(){
System.out.println("Jumping...");
void bite(){
System.out.println("Biting...");
interface BasicAnimal{
void eat();
void sleep();
void speak(){
System.out.println("Hello sir!");
}
@Override
System.out.println("Eating");
@Override
System.out.println("Sleeping");
// Q1 + Q2
pen.changeNib();
// Q3
// Q5
m1.jump();
m1.bite();
lovish.eat();
lovish.sleep();
package com.company;
class Library{
String[] books;
int no_of_books;
Library(){
this.no_of_books = 0;
this.books[no_of_books] = book;
no_of_books++;
void showAvailableBooks(){
if (book == null){
continue;
}
void issueBook(String book){
if (this.books[i].equals(book)){
this.books[i] = null;
return;
addBook(book);
centralLibrary.addBook("Algorithms");
centralLibrary.addBook("C++");
centralLibrary.showAvailableBooks();
centralLibrary.issueBook("C++");
centralLibrary.showAvailableBooks();
centralLibrary.returnBook("C++");
centralLibrary.showAvailableBooks();
package com.company;
import java.util.Scanner;
//import java.util.*;
int a = sc.nextInt();
package com.company;
class C1{
public int x = 5;
int z = 6;
System.out.println(x);
System.out.println(y);
System.out.println(z);
System.out.println(a);
C1 c = new C1();
// c.meth1();
System.out.println(c.x);
System.out.println(c.y);
System.out.println(c.z);
// System.out.println(c.a);
package com.company;
/*
*/
package com.company;
@Override
int i =0;
while(i<40000){
i++;
@Override
int i =0;
while(i<40000){
System.out.println("I am sad!");
i++;
t1.start();
t2.start();
package com.company;
gun1.start();
gun2.start();
package com.company;
class MyThr extends Thread{
super(name);
int i = 34;
System.out.println("Thank you");
// while(true){
// System.out.println("I am a thread");
// }
t1.start();
t2.start();
package com.company;
super(name);
int i = 34;
while(true){
// System.out.println("I am a thread");
}
}
// Ready Queue: T1 T2 T3 T4 T5
t5.setPriority(Thread.MAX_PRIORITY);
t1.setPriority(Thread.MIN_PRIORITY);
t2.setPriority(Thread.MIN_PRIORITY);
t3.setPriority(Thread.MIN_PRIORITY);
t4.setPriority(Thread.MIN_PRIORITY);
t5.setPriority(Thread.MIN_PRIORITY);
t1.start();
t2.start();
t3.start();
t4.start();
t5.start();
package com.company;
int i = 0;
while(true){
// System.out.println("I am a thread");
try {
Thread.sleep(455);
} catch (InterruptedException e) {
e.printStackTrace();
}
i++;
while(true){
// System.out.println("I am a thread");
// try{
// t1.join();
// }
// catch(Exception e){
// System.out.println(e);
// }
t2.start();
package com.company;
while(true){
System.out.println("Good Morning!");
}
}
// while(false){
// try {
// Thread.sleep(200);
// }
// System.out.println(e);
// }
// System.out.println("Welcome");
// }
// p2.setPriority(9);
System.out.println(p1.getPriority());
System.out.println(p2.getPriority());
System.out.println(p2.getState());
// p1.start();
p2.start();
System.out.println(p2.getState());
System.out.println(Thread.currentThread().getState());
package com.company;
int a = 5;
int b = 9;
System.out.println(a+b);
}
}
package com.company;
import java.util.Scanner;
System.out.println(2);
System.out.println(2*i+1);
// RUNTIME ERROR
int k;
k = sc.nextInt();
package com.company;
int a = 6000;
int b = 0;
// Without Try:
// int c = a / b;
// With Try:
try {
int c = a / b;
System.out.println("The result is " + c);
catch(Exception e) {
System.out.println(e);
try (
// code
// code
)
// code
// code
ANOTHER CODE
package com.company;
import java.util.Scanner;
marks[0] = 7;
marks[1] = 56;
marks[2] = 6;
try{
System.out.println("ArithmeticException occured!");
System.out.println(e);
System.out.println("ArrayIndexOutOfBoundsException occured!");
System.out.println(e);
System.out.println(e);
}
Nested Try-Catch in Java
package com.company;
import java.util.Scanner;
marks[0] = 7;
marks[1] = 56;
marks[2] = 6;
while(flag) {
try {
try {
System.out.println(marks[ind]);
flag = false;
} catch (ArrayIndexOutOfBoundsException e) {
}
} catch (Exception e) {
package com.company;
import java.util.Scanner;
@Override
@Override
@Override
public String toString() {
@Override
int a;
a = sc.nextInt();
if (a<9){
try{
System.out.println(e.getMessage());
System.out.println(e.toString());
e.printStackTrace();
System.out.println("Finished");
}
System.out.println("Yes Finished");
@Override
}
@Override
if (r<0){
return result;
// Made By Harry
return result;
try{
// int c = divide(6, 0);
// System.out.println(c);
double ar = area(6);
System.out.println(ar);
catch(Exception e){
System.out.println("Exception");
try{
int a = 50;
int b = 10;
int c = a/b;
return c;
catch(Exception e){
System.out.println(e);
finally {
return -1;
int k = greet();
System.out.println(k);
int a = 7;
int b = 9;
while(true){
try{
System.out.println(a/b);
System.out.println(e);
break;
finally{
b--;
try{
System.out.println(50/3);
}
finally {
2) Write a java program that prints "HaHa" during Arithmetic exception and
"HeHe" during an Illegal argument exception.
3) Write a program that allows you to given. If max retries exceed 5 print
"errors".
import java.util.Scanner;
// Problem 1
// System.out.println(6/0);
// Problem 2
try{
int a = 666/0;
System.out.println("HeHe");
System.out.println("Haha");
// Problem 3
marks[0] = 7;
marks[1] = 56;
marks[2] = 6;
int index;
int i = 0;
try {
index = Sc.nextInt();
System.out.println("The value of marks[index] is " + marks[index]);
break;
catch (Exception e) {
System.out.println("Invalid Index");
i++;
if(i>=5){
System.out.println("Error");
/*
1. + -> Addition
2. - -> Subtraction
3. * -> Multiplication
4. / -> Division
4. Max Multiplier Reached Exception - Don't allow any multiplication input to be greater than
7000
*/
package com.company;
import java.util.ArrayList;
import java.util.Set;
import java.util.TreeSet;
// Set
// TreeSet
Collections in java are available as class and interfaces Folling are few
commonly used collections in java :
import java.util.ArrayList;
import java.util.Set;
import java.util.TreeSet;
// ArrayList
// Set
// TreeSet
}
package com.company;
import java.lang.reflect.Array;
import java.util.*;
l2.add(15);
l2.add(18);
l2.add(19);
l1.add(6);
l1.add(7);
l1.add(4);
l1.add(6);
l1.add(0, 5);
l1.add(0, 1);
l1.addAll(0, l2);
System.out.println(l1.contains(27));
System.out.println(l1.indexOf(6));
System.out.println(l1.lastIndexOf(6));
//l1.clear();
l1.set(1, 566);
System.out.print(l1.get(i));
System.out.print(", ");
package com.company;
import java.util.*;
l2.add(15);
l2.add(18);
l2.add(19);
l1.add(6);
l1.add(7);
l1.add(4);
l1.add(6);
l1.add(0, 5);
l1.add(0, 1);
l1.addAll(0, l2);
l1.addLast(676);
l1.addFirst(788);
System.out.println(l1.contains(27));
System.out.println(l1.indexOf(6));
System.out.println(l1.lastIndexOf(6));
//l1.clear();
l1.set(1, 566);
System.out.print(l1.get(i));
System.out.print(", ");
ArrayDeque in Java
package com.company;
import java.util.ArrayDeque;
ad1.add(56);
ad1.add(9);
ad1.addFirst(5);
System.out.println(ad1.getFirst());
System.out.println(ad1.getLast());
HashSet in Java
package com.company;
import java.util.HashSet;
myHashSet.add(6);
myHashSet.add(8);
myHashSet.add(3);
myHashSet.add(11);
myHashSet.add(11);
System.out.println(myHashSet);
java time -> package for date & time in java from java onwards
Before java 8, java util package used to hold the date time class now these
classes are deprecated
Date in java is stored in the form of a long numer. This long number holds
the number of miliseconds passed since 1 jan 1970
Java assumes that 1900 is the start year which means it calculates years
passed since 1900 whenever We ask it for years passed
System.out.println(System.currentTimeMillis()/1000/3600/24/365);
package com.company;
import java.util.Date;
// System.out.println(System.currentTimeMillis());
System.out.println(d);
System.out.println(d.getTime());
System.out.println(d.getDate());
System.out.println(d.getSeconds());
System.out.println(d.getYear());
package com.company;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.TimeZone;
Calendar c = Calendar.getInstance();
System.out.println(c.getTime());
System.out.println(c.get(Calendar.DATE));
System.out.println(c.get(Calendar.SECOND));
System.out.println(c.get(Calendar.HOUR));
System.out.println(cal.isLeapYear(2018));
System.out.println(TimeZone.getAvailableIDs()[0]);
System.out.println(TimeZone.getAvailableIDs()[1]);
System.out.println(TimeZone.getAvailableIDs()[2]);
package com.company;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
LocalDate d = LocalDate.now();
System.out.println(d);
LocalTime t = LocalTime.now();
System.out.println(t);
LocalDateTime dt = LocalDateTime.now();
System.out.println(dt);
}
}
DateTimeFormatter in Java
package com.company;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
System.out.println(dt);
String myDate = dt.format(df); // Creating date string using date and format
System.out.println(myDate);
package com.company;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
// PS Q1
ar.add("Student 1");
ar.add("Student 2");
ar.add("Student 3");
ar.add("Student 4");
ar.add("Student 5");
ar.add("Student 6");
ar.add("Student 7");
ar.add("Student 8");
ar.add("Student 9");
ar.add("Student 10");
for(Object o: ar){
System.out.println(o);
// PS Q2
Calendar c = Calendar.getInstance();
// PS Q4
String myDate = dt.format(df); // Creating date string using date and format
System.out.println(myDate);
// PS Q5
s.add(5);
s.add(6);
s.add(46);
s.add(60);
s.add(9);
s.add(6);
System.out.println(s);
package com.company;
@Override
@Override
@Override
@Override
@Override
@Override
@Override
class CustomCalculator {
if(a>100000 || b>100000){
}
if(a==8 || b==9) {
return a + b;
if(a>100000 || b>100000){
return a - b;
if(a>100000 || b>100000){
return a * b;
if(a>100000 || b>100000){
if(b==0){
throw new CannotDivideByZeroException();
return a / b;
// c.add(8, 9);
// c.divide(6, 0);
// c.divide(600000000, 40);
c.multiply(5, 9888);
/*
1. + -> Addition
2. - -> Subtraction
3. * -> Multiplication
4. / -> Division
4. Max Multiplier Reached Exception - Don't allow any multiplication input to be greater than
7000
*/
package com.company;
/*
Create a library management system which is capable of issuing books to the students.
1. Book name
2. Book Author
3. Issued to
4. Issued on
User should be able to add books, return issued books, issue books
Assume that all the users are registered with their names in the central database
*/
package com.company;
a = 98;
arr[0] = 98;
}
static void tellJoke(){
"Plagiarism!");
// tellJoke();
//int x = 45;
//change(x);
// change2(marks);
// Method Overloading
foo();
foo(3000);
foo(3000, 4000);
package com.company;
/**
* This class is to demonstrate what javadoc is and how it is used in the java industry
* @version 0.1
* @since 2002
*/
}
}
package com.company;
/**
*/
/**
*/
/**
* Hello this is a method and this is the most beautiful method of this class
* @throws Exception if i is 0
*/
int c;
c= i+ j;
return c;
Annotations in Java
package com.company;
@FunctionalInterface
interface myFunctionalInteface{
void thisMethod();
// void thisMethod2();
@Override
System.out.println("Time is 8PM");
@Deprecated
return a+b;
}
@SuppressWarnings("deprecation")
phone.showTime();
phone.sum(5, 6);
Java Generics
package com.company;
import java.util.ArrayList;
import java.util.Scanner;
int val;
private T1 t1;
private T2 t2;
this.val = val;
this.t1 = t1;
this.t2= t2;
public T2 getT2() {
return t2;
this.t2 = t2;
return val;
this.val = val;
public T1 getT1() {
return t1;
this.t1 = t1;
}
// arrayList.add("str1");
arrayList.add(54);
arrayList.add(643);
// arrayList.add(new Scanner(System.in));
// System.out.println(a);
System.out.println(str + int1);
package com.company;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Scanner;
/*
try {
myFile.createNewFile();
} catch (IOException e) {
e.printStackTrace();
try {
fileWriter.write("This is our first file from this java course\nOkay now bye");
fileWriter.close();
} catch (IOException e) {
e.printStackTrace();
}
// Reading a file
try {
while(sc.hasNextLine()){
System.out.println(line);
sc.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
*/
// Deleting a file
if(myFile.delete()){
else{
}
Advanced Java 2 - Practice Set
package com.company;
import java.io.FileWriter;
import java.io.IOException;
class MyDeprecated{
@Deprecated
void meth1(){
interface MyInt{
void display();
// d.meth1();
int i = 19;
String table = "";
table += "\n";
try {
fileWriter.write(table);
fileWriter.close();
} catch (IOException e) {
e.printStackTrace();
package com.company;
import java.util.ArrayList;
/*
Create a library management system which is capable of issuing books to the students.
1. Book name
2. Book Author
3. Issued to
4. Issued on
User should be able to add books, return issued books, issue books
Assume that all the users are registered with their names in the central database
*/
class Book{
this.name = name;
this.author = author;
@Override
return "Book{" +
'}';
class MyLibrary{
this.books = books;
}
this.books.add(book);
System.out.println("The book has been issued from the library to " + issued_to);
this.books.remove(book);
this.books.add(b);
// Exercise 7 Solution
bk.add(b1);
bk.add(b2);
Book b3 = new Book("Algorithms3", "CLRS3");
bk.add(b3);
bk.add(b4);
System.out.println(l.books);
l.issueBook(b3, "Harry");
System.out.println(l.books);
package com.company;
import java.util.ArrayList;
/*
Create a library management system which is capable of issuing books to the students.
1. Book name
2. Book Author
3. Issued to
4. Issued on
User should be able to add books, return issued books, issue books
Assume that all the users are registered with their names in the central database
*/
class Book{
this.name = name;
this.author = author;
@Override
return "Book{" +
'}';
class MyLibrary{
this.books = books;
}
public void addBook(Book book){
this.books.add(book);
System.out.println("The book has been issued from the library to " + issued_to);
this.books.remove(book);
this.books.add(b);
// Exercise 7 Solution
bk.add(b1);
bk.add(b2);
bk.add(b4);
System.out.println(l.books);
l.issueBook(b3, "Harry");
System.out.println(l.books);