SlideShare a Scribd company logo
Name – M ADHITYA
ALL OF MY Java PROGRAMS
[
Code:
package com.company;//TIP To <b>Run</b> code, press <shortcut actionId="Run"/> or
// click the <icon src="AllIcons.Actions.Execute"/> icon in the gutter.
public class Main {
public static void main(String[] args) {
//TIP Press <shortcut actionId="ShowIntentionActions"/> with your caret at the
highlighted text
// to see how IntelliJ IDEA suggests fixing it.
System.out.println("Hello World");
}
}
Output:
Hello World
]
[
Code:
// storing integer in variable in java and printing
package com.company;//TIP To <b>Run</b> code, press <shortcut actionId="Run"/> or
// click the <icon src="AllIcons.Actions.Execute"/> icon in the gutter.
public class Main {
public static void main(String[] args) {
//TIP Press <shortcut actionId="ShowIntentionActions"/> with your caret at the
highlighted text
// to see how IntelliJ IDEA suggests fixing it.
int number = 8; //storing integer
System.out.println(number);
}
}
Output:
8
]
[
Code:
package com.company;//TIP To <b>Run</b> code, press <shortcut actionId="Run"/> or
// click the <icon src="AllIcons.Actions.Execute"/> icon in the gutter.
public class Main {
public static void main(String[] args) {
//TIP Press <shortcut actionId="ShowIntentionActions"/> with your caret at the
highlighted text
// to see how IntelliJ IDEA suggests fixing it.
System.out.print("The sum of the numbers is: ");
int num1 = 2;
int num2 = 3;
int num3 = 4;
int sum = num1 + num2 + num3; //sum of three numbers
System.out.print(sum);
}
}
Output:
The sum of the numbers is: 9
Process finished with exit code 0
]
[
Code:
package com.company;
public class CH_04_Literals {
public static void main(String[] args) {
byte age = 34;
System.out.print(age);
char ch = 'A';
float f1 = 5.6f;
double d1 = 5.66D; //By default decimal no. is double so can choose to not
write D or d
long ageDino = 5666666666666666l; //can write capital L
short age3 = 87; //no need to write s for short literal
boolean a = true;
String str = " Adhi";
System.out.print(str);
}
}
Output:
34 Adhi
]
[
Code:
package com.company;
import java.util.Scanner; //Importing external Scanner class(import statement)
public class CH_05_TakingInpu {
public static void main(String[] args) {
System.out.print("Taking Input From the User: ");
Scanner sc = new Scanner(System.in);
System.out.println("enter number 1: ");
int a = sc.nextInt();
System.out.println("enter number 2: ");
int b = sc.nextInt();
int sum = a+b;
System.out.println("the sum of these numbers: ");
System.out.print(sum);
}
}
Output:
Taking Input From the User: enter number 1:
2
enter number 2:
3
the sum of these numbers:
5
]
[
Code:
package com.company;
import java.util.Scanner; //Importing external Scanner class(import statement)
public class CH_05_TakingInpu {
public static void main(String[] args) {
System.out.print("Taking Input From the User: ");
Scanner sc = new Scanner(System.in);
System.out.println("enter number 1: ");
// int a = sc.nextInt();
float a = sc.nextFloat();
System.out.println("enter number 2: ");
// int b = sc.nextInt();
float b = sc.nextFloat();
float sum = a+b;
System.out.println("the sum of these numbers: ");
System.out.print(sum);
}
}
Output:
Taking Input From the User: enter number 1:
2
enter number 2:
3
the sum of these numbers:
5.0
]
[
Code:
package com.company;
import java.util.Scanner; //Importing external Scanner class(import statement)
public class CH_05_TakingInpu {
public static void main(String[] args) {
System.out.print("Taking Input From the User: ");
Scanner sc = new Scanner(System.in);
String str = sc.nextLine(); //nextLine method is used to read whole string
line, and next method is used to only read first word
System.out.print(str);
}
}
Output:
Taking Input From the User: 2
2
]
[
Code:
package com.company;
import java.util.Scanner; //Importing external Scanner class(import statement)
public class CH_05_TakingInpu {
public static void main(String[] args) {
System.out.print("Taking Input From the User: ");
Scanner sc = new Scanner(System.in);
String str = sc.next();
System.out.print(str);
}
}
Output:
Taking Input From the User: Adhi
Adhi
]
[
Code:
package com.company;
// import java.util.Scanner; //Importing external Scanner class(import statement)
public class CH_05_TakingInpu {
public static void main(String[] args) {
//calculating CGPA of 3 subjects
float sub1 = 45;
float sub2 = 97;
float sub3 = 48;
float cgpa = (sub1 + sub2 + sub3)/30;
System.out.println(cgpa);
}
}
Output:
6.3333335
]
[
Code:
package com.company;
import java.util.Scanner; //Importing external Scanner class(import statement)
public class CH_05_TakingInpu {
public static void main(String[] args) {
//Taking Name as input and wishing them using string concatenation
System.out.println("What is your name: ");
Scanner sc = new Scanner(System.in);
String name = sc.next();
System.out.println("Hello "+ name + " Have a good day!");
}
}
Output:
What is your name:
M Adhitya
Hello M Have a good day!
]
[
Code:
package com.company;
import java.util.Scanner; //Importing external Scanner class(import statement)
public class CH_05_TakingInpu {
public static void main(String[] args) {
//Checking if input is Integer or not through Boolean
System.out.println("Enter your number: ");
Scanner sc = new Scanner(System.in);
System.out.println(sc.hasNextInt());
}
}
Output:
Enter your number:
23.8
false
]
[
Code:
package com.company;
public class CWH_CH02_Operators {
public static void main(String[] args) {
int a = 4; //Operators
int b = 6*a;
System.out.println(b);
}
}
Output:
24
]
[
Code:
package com.company;
public class CWH_CH02_Operators {
public static void main(String[] args) {
int a = 4; //Operators
//int b = 6*a;
int b = 9;
b+=3;
System.out.println(b);
}
}
Output:
12
]
[
Code:
package com.company;
public class CWH_CH02_Operators {
public static void main(String[] args) {
int a = 4; //Operators
//int b = 6*a;
int b = 9;
b+=3;
System.out.println(b);
System.out.println(6==8);
// = is assignment operator and == is comparison operator
System.out.println(64>9);
}
}
Output:
12
false
true
]
[
Code:
package com.company;
public class CWH_CH02_Operators {
public static void main(String[] args) {
int a = 4; //Operators
//int b = 6*a;
int b = 9;
b+=3;
System.out.println(b);
System.out.println(6==8);
// = is assignment operator and == is comparison operator
System.out.println(64>9);
// && is logical operator
System.out.println(64>5 && 64>8);
}
}
Output:
12
false
true
true
]
[
Code:
package com.company;
public class CWH_CH02_Operators {
public static void main(String[] args) {
int a = 5*6 - 34/5; //Precedence and Associativity in Java
int b = 34/5 - 60*5;
System.out.println(a);
System.out.println(b);
}
}
Output:
24
-294
]
[
Code:
package com.company;
public class CWH_CH02_Operators {
public static void main(String[] args) {
//Precedence and Associativity in Java
int x = 6;
int y = 1;
int k = x*y/2;
System.out.println(k);
}
}
Output:
3
]
[
Code:
package com.company;
public class CWH_CH02_Operators {
public static void main(String[] args) {
//Precedence and Associativity in Java
int x = 6;
int y = 1;
int k = x*y/2;
System.out.println(k);
int a = 1;
int b = 2;
int c = 3;
int d = (b*b - 4*a*c)/(2*a);
System.out.println(d);
}
}
Output:
3
-4
]
[
Code:
package com.company;
public class CWH_10_resulting_data_type_ps1 {
public static void main(String[] args) {
int a = 654 + 6; //Resulting Data Type by Adding etc. 2 different data type
byte x = 5;
float b= 3.56f + x;
int y = 6;
short z = 8;
System.out.println(b);
}
}
Output:
8.559999
]
[
Code:
package com.company;
public class CWH_10_resulting_data_type_ps1 {
public static void main(String[] args) {
/* int a = 654 + 6;
byte x = 5;
float b= 3.56f + x;
int y = 6;
short z = 8;
System.out.println(b);*/
// Increment and Decrement Operators
int i = 56;
System.out.println(i++); // i++ means print i then increment it
System.out.println(i);
System.out.println(++i); // ++i means print increment then print i
System.out.println(i);
}
}
Output:
56
57
58
58
]
[
Code:
package com.company;
public class CWH_10_resulting_data_type_ps1 {
public static void main(String[] args) {
int y = 7;
System.out.println(++y*8);
char ch = 'a';
System.out.println(++ch); //Increment
}
}
Output:
64
B
]
[
Code:
package com.company;
import java.util.Scanner;
//Calculating CBSE board percentage
public class CWH_10_resulting_data_type_ps1 {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("Enter your Physics marks: ");
int physics = scan.nextInt() ;//nextInt() is used for input
System.out.println("Enter your English marks: ");
int english = scan.nextInt();
System.out.println("Enter your Chemistry marks: ");
int chemistry = scan.nextInt();
System.out.println("Enter your Mathematics marks: ");
int mathematics = scan.nextInt();
System.out.println("Enter your computer science marks:");
int computer = scan.nextInt();
float r = ((physics + english+chemistry+mathematics+computer)/500.0f)*100;
System.out.println("Your Percentage is:");
System.out.println(r);
}
}
Output:
Enter your Physics marks:
95
Enter your English marks:
97
Enter your Chemistry marks:
84
Enter your Mathematics marks:
86
Enter your computer science marks:
92
Your Percentage is:
90.8
]
[
Code:
package com.company;
public class CWH_10_resulting_data_type_ps1 {
public static void main(String[] args) {
float a = 7/4.0f *9/2.0f ; // arithmetic between int and i t is int, to get
correct value convert to float
System.out.println(a);
}
}
Output:
7.875
]
[
Code:
package com.company;
public class CWH_CH12_ps2_pr01 {
public static void main(String[] args) {
//Type casting used as (char) to convert (grade+8) which is int to char
char grade = 'B';
grade = (char)(grade+8); //In type casting no need to write type in start as
usual
System.out.println(grade);
grade = (char)(grade-8);
System.out.println(grade);
}
}
Output:
J
B
]
[
Code:
package com.company;
import java.util.Scanner;
public class CWH_CH12_ps2_pr01 {
public static void main(String[] args) {
//To check if Given number is greater than user defined or not using user
defined functioned
Scanner sc = new Scanner(System.in);
int a = sc.nextInt();
System.out.println(a>8);
}
}
Output:
4
False
]
[
Code:
package com.company;
import java.util.Scanner;
public class CWH_CH12_ps2_pr01 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int v = sc.nextInt();
int u = sc.nextInt();
int a = sc.nextInt();
int s = sc.nextInt();
float r = (float)(v*v - u*u)/(2*a*s);
System.out.println(r);
}
}
Output:
2
3
4
5
-0.125
]
[
Code:
package com.company;
public class CWH_16_conditionals{
public static void main(String[] args) {
int age = 20;
if (age>18){
System.out.println("yes boy you can drive");
}
// else{
// System.out.println("No boy you cannot drive yet");
// }
}
}
Output:
yes boy you can drive
]
[
Code:
package com.company;
public class CWH_16_conditionals{
public static void main(String[] args) {
int age = 20;
if (age!=18){ //Using relational operators
System.out.println("yes boy you can drive");
}
else{
System.out.println("No boy you cannot drive yet");
}
}
}
Output:
yes boy you can drive
]
[
Code:
package com.company;
public class Main {
public static void main(String[] args) {
boolean a = true;
boolean b = false;
if (a&&b){
System.out.println("Y");
}
else{
System.out.println("N");
}
}
}
Output:
N
]
[
Code:
package com.company;
public class Main {
public static void main(String[] args) {
boolean a = true;
boolean b = false;
boolean c = true;
if (a&&b&&c){
System.out.println("Y");
}
else{
System.out.println("N");
}
}
}
Output:
N
]
[
Code:
package com.company;
import java.util.Scanner;
public class CWH_16_conditionals{
public static void main(String[] args) {
int age;
Scanner sc = new Scanner(System.in);
age = sc.nextInt();
if (age>56){
System.out.println("You are experienced");
}
else if (age>46){
System.out.println("You are semi-experienced");
}
else if (age>36){
System.out.println("You are semi-semi-experienced");
}
else{
System.out.println("You are not experienced");
}
}
}
Output:
38
You are semi-semi-experienced
]
[
Code:
package com.company;
import java.util.Scanner;
public class CWH_16_conditionals{
public static void main(String[] args) {
int age;
System.out.println("Enter age");
Scanner sc = new Scanner(System.in);
age = sc.nextInt();
switch(age){
case 18:
System.out.println("You are an Adult");
break;
case 20:
System.out.println("You are going to get a job");
break;
case 60:
System.out.println("You are going to get retired");
break;
default:
System.out.println("Enjoy your Life!");
}
}
}
Output:
Enter age
38
Enjoy your Life!
]
[
Code:
package com.company;
import java.util.Scanner;
public class CWH_16_conditionals{
public static void main(String[] args) {
String var = "Harry";
Scanner sc = new Scanner(System.in);
switch(var){
case "Saurabh":
System.out.println("You are an Adult");
break;
case "Harry" :
System.out.println("You are going to get a job");
break;
case "Adhitya" :
System.out.println("You are going to get retired");
break;
default:
System.out.println("Enjoy your Life!");
}
}
}
Output:
You are going to get a job
]
[
Code:
package com.company;
import java.util.Scanner;
public class CWH_16_conditionals{
public static void main(String[] args) {
String var = "Harry";
Scanner sc = new Scanner(System.in);
switch (var) {
case "Saurabh" -> System.out.println("You are an Adult"); //Enhanced
switch statement
case "Harry" -> System.out.println("You are going to get a job");
case "Adhitya" -> System.out.println("You are going to get retired");
default -> System.out.println("Enjoy your Life!");
}
}
}
Output:
You are going to get a job
]
[
Code:
package com.company;
import java.util.Scanner;
public class CWH_16_conditionals{
public static void main(String[] args) {
int a = 10;
if (a==11){
System.out.println("I am 11");
}
else{
System.out.println("I am not 11");
}
}
}
Output:
I am not 11
]
[
Code:
package com.company;
import java.util.Scanner;
public class CWH_16_conditionals{
public static void main(String[] args) {
//Find if a student is pass or fail
// use byte as number is below or equal to 100
byte m1,m2,m3;
Scanner sc = new Scanner(System.in);
System.out.println("Enter your marks in Physics");
m1 = sc.nextByte();
System.out.println("Enter your marks in Chemistry");
m2 = sc.nextByte();
System.out.println("Enter your marks in Mathematics");
m3 = sc.nextByte();
float avg = (m1+m2+m3)/3.0f;
if (avg>=40 && m1>=33 && m2>=33 && m3>=33){
System.out.println("Congrats, you are promoted");
}
else{
System.out.println("repeat the course");
}
}
}
Output:
Enter your marks in Physics
95
Enter your marks in Chemistry
84
Enter your marks in Mathematics
86
Congrats, you are promoted
]
[
Code:
package com.company;
import java.util.Scanner;
public class CWH_16_conditionals{
public static void main(String[] args) {
//Problem- write java problem to find out the day of the week given number(1-
Monay, 2-Tuesday, etc.)
Scanner sc = new Scanner(System.in);
System.out.println("enter number of day: ");
int day = sc.nextInt();
switch(day){
case 1-> System.out.println("Monday");
case 2-> System.out.println("Tuesday");
case 3-> System.out.println("Wednesday");
case 4-> System.out.println("Thursday");
case 5-> System.out.println("Friday");
case 6-> System.out.println("Saturday");
case 7-> System.out.println("Sunday");
}
}
}
Output:
enter number of day:
2
Tuesday
]
[
Code:
package com.company;
import java.util.Scanner;
public class CWH_16_conditionals{
public static void main(String[] args) {
//Problem - From URL from user find out what type of website it is
Scanner sc = new Scanner(System.in);
System.out.println("Enter URL");
String website = sc.nextLine();
if (website.endsWith(".org")){
System.out.println("Organizational website");
}
else if (website.endsWith(".com")){
System.out.println("Commercial website");
}
else if (website.endsWith(".in")){
System.out.println("Indian website");
}
}
}
Output:
Enter URL
https://www.youtube.com
Commercial website
]
[
Code:
package com.company;
import java.util.Scanner;
public class CWH_16_conditionals{
public static void main(String[] args) {
int i = 1;
System.out.println("Using Loops: ");
while(i<=3){
System.out.println(i);
i++;
}
System.out.println("Finished using Loops! ");
}
}
Output:
Using Loops:
1
2
3
Finished using Loops!
]
[
Code:
package com.company;
public class CWH_22_do_while {
public static void main(String[] args) {
int a =0;
while(a<5){
System.out.println(a);
a++;
}
}
}
Output:
0
1
2
3
4
]
[
Code:
package com.company;
public class CWH_22_do_while {
public static void main(String[] args) {
int b=10;
do{
System.out.println(b); //do-while loop executes first loop without
checking condition
b++;
}while(b<5);
}
}
Output:
10
]
[
Code:
package com.company;
public class CWH_22_do_while {
public static void main(String[] args) {
int c =1;
do{
System.out.println(c);
c++;
}while(c<=45);
}
}
Output:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
]
[
Code:
package com.company;
public class CWH_23_for_loop {
public static void main(String[] args) {
for (int i =1;i<=10; i++){
System.out.println(i);
}
}
}
Output:
1
2
3
4
5
6
7
8
9
10
]
[
Code:
package com.company;
public class CWH_23_for_loop {
public static void main(String[] args) {
int n = 5;
for (int i = 0; i<=5; i++){
System.out.println(2*i+1);
}
}
}
Output:
1
3
5
7
9
11
]
[
Code:
package com.company;
public class CWH_23_for_loop {
public static void main(String[] args) {
for(int i =5; i!=0; i--){
System.out.println(i);
}
}
}
Output:
5
4
3
2
1
]
[
Code:
package com.company;
public class CWH_23_for_loop {
public static void main(String[] args) {
//break and continue using loops
for (int i =0; i<5; i++){
System.out.println(i);
System.out.println("Java is great");
if (i==2){
System.out.println("Ending the loop");
break;
}
}
}
}
Output:
0
Java is great
1
Java is great
2
Java is great
Ending the loop
]
[
Code:
package com.company;
public class CWH_24_break_and_continue {
public static void main(String[] args) {
//Practice Problem 1 - Create pattern of * using loop
int n =4;
for (int i=n; i>0; i--){
for (int j=0; j<i;j++){
System.out.print("*");
}
System.out.println("n");
}
}
}
Output:
****
***
**
*
]
[
Code:
package com.company;
public class CWH_24_break_and_continue {
public static void main(String[] args) {
//Practice Problem 2 - sum of first n even numbers
int sum=0;
int n=4;
for (int i=0;i<n;i++){
sum = sum + (2*i);
}
System.out.print("Sum of first %d even numbers ");
System.out.println(sum);
}
}
Output:
Sum of first %d even numbers 12
Process finished with exit code 0
]
[
Code:
package com.company;
public class CWH_24_break_and_continue {
public static void main(String[] args) {
//Problem - Write a program to print multiplication of a number n
int n=5;
for (int i=1; i<=10;i++){
System.out.printf("%d X %d = %d", n,i, n*i);
System.out.println("n");
}
}
}
Output:
5 X 1 = 5
5 X 2 = 10
5 X 3 = 15
5 X 4 = 20
5 X 5 = 25
5 X 6 = 30
5 X 7 = 35
5 X 8 = 40
5 X 9 = 45
5 X 10 = 50
]
[
Code:
package com.company;
import java.util.Scanner;
import java.util.Scanner;
public class CWH_24_break_and_continue {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a number: ");
int number = scanner.nextInt();
scanner.close();
long factorial = 1;
for (int i = 1; i <= number; i++) {
factorial *= i;
}
System.out.println("Factorial of " + number + " is: " + factorial);
}
}
Output:
Enter a number: 6
Factorial of 6 is: 720
]
[
Code:
package com.company;
import java.util.Scanner;
public class CWH_24_break_and_continue {
public static void main(String[] args) {
//Problem- Factorial using while loop
int n=5;
// what is factorial = n*n-1*n-2..1
int i =1;
//5!=5*4*3*2*1
int factorial =1;
while(i<=n){
factorial*=i;
i++;
}
System.out.println(factorial);
}
}
Output:
120
]
[
Code:
package com.company;
import java.util.Scanner;
public class CWH_24_break_and_continue {
public static void main(String[] args) {
//print sum of the numbers in product side of multiplication table of 8
int n=8;
int sum=0;
for (int i=1; i<=10; i++){
sum+=n*i;
}
System.out.println(sum);
}
}
Output:
440
]
[
Code:
package com.company;
public class cwh_26_arrays {
public static void main(String[] args) {
//Classroom of 5 marks - you have to store marks of 500 students
//You have 2 options-
//1. create 5 variables
//2.Use arrays
//Array is a collection of similar types of data
// array format is [datatype[] arrayName]
int [] marks = new int[5];
marks[0]= 50;
marks[1]=70;
marks[2]=30;
marks[3]=86;
marks[4]=93;
System.out.println(marks[4]);
}
}
Output:
93
]
[
Code:
package com.company;
public class cwh_26_arrays {
public static void main(String[] args) {
//Other ways of declaring arrays
//method -2
int []marks;
marks = new int[5];
//method -3
int [] list ={100,70,80,45,71};
System.out.println(list[2]);
}
}
Output:
80
]
[
Code:
package com.company;
public class cwh_27_arrays {
public static void main(String[] args) {
int [] marks = {100,30,80,96,78};
System.out.println(marks[3]);
System.out.println(marks.length);
float [] marks1 = {45.1f, 76.3f, 67.3f, 98.5f, 46};
System.out.println(marks1[4]);
String [] students = {"Harry", "Lovish", "Rohan", "Shubham"};
System.out.println(students.length);
}
}
Output:
96
5
46.0
4
]
[
Code:
package com.company;
public class cwh_27_arrays {
public static void main(String[] args) {
int [] marks = {100,30,80,96,78};
System.out.println(marks[3]);
System.out.println(marks.length);
float [] marks1 = {45.1f, 76.3f, 67.3f, 98.5f, 46};
System.out.println(marks1[4]);
String [] students = {"Harry", "Lovish", "Rohan", "Shubham"};
System.out.println(students.length);
//Displaying array
// Forward using for loop
for (int i=0; i<marks.length; i++){
System.out.println(i);
}
// reverse using for loop
for (int i = marks.length -1; i>=0; i--){
System.out.println(i);
}
//for each loop for displaying
System.out.println("Printing using for-each loop");
for (int element: marks){
System.out.println(element);
}
}
}
Output:
96
5
46.0
4
0
1
2
3
4
4
3
2
1
0
Printing using for-each loop
100
30
80
96
78
]
[
Code:
package com.company;
public class cwh_29_Practice_Set_6 {
public static void main(String[] args) {
//Problem - create an array of 5 floats and find their sum
float [] marks = {45.7f, 34.6f, 100.0f, 93.5f, 94.8f};
float sum =0;
for (float element : marks){
sum = sum+ element;
}
System.out.println("the value of sum is: ");
System.out.println(sum);
}
}
Output:
the value of sum is:
368.59998
]
[
Code:
package com.company;
public class cwh_29_Practice_Set_6 {
public static void main(String[] args) {
//Problem - create an array of 5 floats and find their sum
float [] marks = {45.7f, 34.6f, 100.0f, 93.5f, 94.8f};
float num = 45.7f;
boolean isInArray= false;
for (float element : marks){
if (num==element){
isInArray=true;
break;
}
}
if (isInArray){
System.out.println("the value is present in the Array");
}
else{
System.out.println("the value is not present in the Array");
}
}
}
Output:
the value is present in the Array
]
[
Code:
package com.company;
public class cwh_29_Practice_Set_6 {
public static void main(String[] args) {
//Problem - calculate average of marks of an array containing marks of all
students in physics
int [] marks = {34, 56, 78, 98, 100};
int sum = 0;
for (int i =0; i< marks.length; i++){
sum = sum + i;
}
int avg = sum/marks.length;
System.out.print("Average of the numbers in the array is ");
System.out.println(avg);
//Using for each loop
for (int element : marks){
sum = sum + element;
}
System.out.println("Average using for each loop is "+ sum/marks.length);
}
}
Output:
Average of the numbers in the array is 2
Average using for each loop is 75
]
[
Code:
package com.company;
public class cwh_29_Practice_Set_6 {
public static void main(String[] args) {
//Problem - create a java program to add 2 matrices of size 2X3
// we will do it using arrays
int [][]mat1 = {{1,2,3},
{4,5,6}}; // as in 2-D arrays it is equivalent to [row][column]
int [][] mat2 = {{2,5,6},
{12, 43, 1}};
int [][] result ={{0,0,0},
{0,0,0}};
for (int i=0; i< mat1.length; i++){
for (int j=0; j< mat1[i].length; j++){
result[i][j] = mat1[i][j]+ mat2[i][j];
System.out.printf(result[i][j]+ " ");
}
System.out.print("n");
}
}
}
Output:
3 7 9
16 48 7
]
[
Code:
package com.company;
public class cwh_31_methods {
public static void main(String[] args) {
int a= 5;
int b=7;
int c= (a+b)*5;
System.out.println(c);
}
}
Output:
60
]
[
Code:
package com.company;
public class cwh_31_methods {
public static void main(String[] args) {
int a= 5;
int b=7;
int c;
if (a>b){
c = a+b;
}
else{
c = (a+b)*5;
}
int a1=2;
int b1=1;
int c1;
if (a1>b1){
c1 =a1+b1;
}
else{
c1 = (a1+b1)*5;
}
System.out.println(c);
System.out.println(c1);
}
}
Output:
60
3
]
[
Code:
package com.company;
public class cwh_31_methods {
//Java methods is equivalent to functions in Python
static int logic(int x, int y){
int z;
if (x>y){
z = x+y;
}
else{
z = (x+y)*5;
}
return z;
}
public static void main(String[] args) {
int a= 5;
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);
}
}
Output:
60
3
]
[
Code:
package com.company;
public class cwh_31_methods {
//Java method belongs to the class. Without static keyword, we have to make object and call
as shown
// only static methods can be called directly within public static void main(String[] args)
// Method invocation using object creation
int logic(int x, int y){
int z;
if (x>y){
z = x+y;
}
else{
z = (x+y)*5;
}
return z;
}
public static void main(String[] args) {
int a= 5;
int b=7;
int c;
cwh_31_methods obj = new cwh_31_methods();
c =obj.logic(a,b);
int a1=2;
int b1=1;
int c1;
c1 = obj.logic(a1, b1);
System.out.println(c);
System.out.println(c1);
}
}
Output:
60
3
]
[
Code:
package com.company;
public class cwh_32_method_overloading {
static void tellJoke(){
System.out.println("I invented a new word n" +
"Plagiarism!");
}
public static void main(String[] args) {
tellJoke();
}
}
Output:
I invented a new word
Plagiarism!
]
[
Code:
package com.company;
public class cwh_32_method_overloading {
static void change(int a){
a = 98;
}
public static void main(String[] args) {
int x = 45;
change(x); //copy of x's value goes to method change and hence actual value of x doesnt
change
System.out.println( "the value of x after change method is "+ x);
}
}
Output:
the value of x after change method is 45
]
[
Code:
package com.company;
public class cwh_32_method_overloading {
static void change(int a){
a = 98;
}
static void change2(int [] arr){
arr[0]= 98;
}
public static void main(String[] args) {
// Case 1 - Changing the integer
//int x = 45;
// change(x); //copy of x's value goes to method change and hence actual value of x
doesnt change
// System.out.println( "the value of x after change method is "+ x);
// value of x didn't change. It will change only if reference is passed and not the copy
of the object
//Case 2- Changing the Array
int [] marks = {52, 76, 98, 56, 78, 93};
change2(marks); // marks is reference. As reference is passed into change2,
// arr and marks refer to the same array and marks[0] value changes
System.out.println("the first value of array after change2 "+ marks[0]);
}
}
Output:
the first value of array after change2 98
]
[
Code:
package com.company;
public class cwh_32_method_overloading {
//Method Overloading - same name methods with different parameters
static void foo(){
System.out.println("Good morning Bro! ");
}
static void foo(int a){
System.out.println("Good morning "+ a + " Bro!");
}
public static void main(String[] args) {
foo();
foo(34);
} // a is parameter while 34 is argument
}//Arguments are actual!
//Cannot do overloading by changing return type. Void is return type, int is return type.
//Both void and int return types are written beside static
Output:
Good morning Bro!
Good morning 34 Bro!
]
[
Code:
package com.company;
public class cwh_33_varargs {
static int sum(int a, int b){
return a+b;
}
static int sum(int a, int b,int c){
return a+b+c;
}
// Varargs method to replace all the above methods
static int sum(int ...arr){
// Available as int [] arr
int result = 0;
for (int a : arr){
result+=a;
}
return result;
}
public static void main(String[] args) {
System.out.println("Welcome to Varargs Tutorial");
System.out.println("Sum of 4 and 5 is "+ sum(4,5));
System.out.println("Sum of 4 and 5 is "+ sum(4,3,5));
// further if we want to get sum for n numbers we cannot keep doing overloading
// to solve this we use varargs
System.out.println("Sum of Random number of numbers by varargs is "+
sum(4,5,6,7,8,9,2,122,2332));
}
}
Output:
Welcome to Varargs Tutorial
Sum of 4 and 5 is 9
Sum of 4 and 5 is 12
Sum of Random number of numbers by varargs is 2495
]
[
Code:
package com.company;
public class cwh_33_varargs {
static int sum(int a, int b){
return a+b;
}
static int sum(int a, int b,int c){
return a+b+c;
}
// Varargs method to replace all the above methods
static int sum(int x, int ...arr){
// Available as int [] arr
int result = x;
for (int a : arr){
result+=a;
}
return result;
}
public static void main(String[] args) {
System.out.println("Welcome to Varargs Tutorial");
System.out.println("Sum of 4 and 5 is "+ sum(4,5));
System.out.println("Sum of 4 and 5 is "+ sum(4,3,5));
// further if we want to get sum for n numbers we cannot keep doing overloading
// to solve this we use varargs
System.out.println("Sum of Random number of numbers by varargs is "+
sum(4,5,6,7,8,9,2,122,2332));
}
}
Output:
Welcome to Varargs Tutorial
Sum of 4 and 5 is 9
Sum of 4 and 5 is 12
Sum of Random number of numbers by varargs is 2495
]
[
Code:
package com.company;
//Recursion is when the function/method calls itself when it is executed
//factorial can be done using recursion
public class cwh_34_recursion {
static int factorial(int n){
if (n==0 || n==1){
return 1;
}
else{
return n* factorial(n-1);
}
}
public static void main(String[] args) {
int n=4;
System.out.println("Factorial of 4 is "+ factorial(n));
}
}
Output:
Factorial of 4 is 24
]
[
Code:
package com.company;
//Problem- multiplication of a number using Java methods
public class cwh_34_recursion {
static void multiplication(int n){
for (int i =0; i<=10; i++){
System.out.printf("%d X %d = %dn", n, i, n*i);
}
}
public static void main(String[] args) {
multiplication(7);
}
}
Output:
7 X 0 = 0
7 X 1 = 7
7 X 2 = 14
7 X 3 = 21
7 X 4 = 28
7 X 5 = 35
7 X 6 = 42
7 X 7 = 49
7 X 8 = 56
7 X 9 = 63
7 X 10 = 70
]
[
Code:
package com.company;
//Problem- Create desired pattern using Java methods
public class cwh_34_recursion {
static void star(int n){
for (int i=1; i<=n; i++){
for (int j=0; j<i; j++){
System.out.print("*");
}
System.out.println();
}
}
public static void main(String[] args) {
star(4);
}
}
Output:
*
**
***
****
]
[
Code:
package com.company;
//Problem-write a recursive function to find sum of first n natural numbers
public class cwh_34_recursion {
static int sumRec(int n){
if (n==1){
return 1;
}
else{
return n+ sumRec(n-1);
}
}
public static void main(String[] args) {
int c = sumRec(4);
System.out.print("Sum of n natural numbers using recursion function is ");
System.out.println(c);
}
}
Output:
Sum of n natural numbers using recursion function is 10
]
[
Code:
package com.company;
//Problem- Create desired pattern using Java methods
public class cwh_34_recursion {
static void star(int n){
for (int i=1; i<=n; i++){
for (int j=n; j>i -1; j--){
System.out.print("*");
}
System.out.println();
}
}
public static void main(String[] args) {
star(4);
}
}
Output:
****
***
**
*
]
[
Code:
package com.company;
//Problem- write a function to print nth term of the fibonnaci series using recursion
// fibonacci series - 0,1,1,2,3,5,8,13,21,34,...
public class cwh_34_recursion {
static int fib(int n){
if (n==1){
return 0;
}
else if (n==2){
return 1;
}
else{
return fib(n-1)+fib(n-2);
}
}
public static void main(String[] args) {
int c = fib(8);
System.out.print("nth term of the Fibonacci series is ");
System.out.println(c);
}
}
Output:
nth term of the Fibonacci series is 13
]
[
Code:
package com.company;
//custom class has attributes within it
//there can be only one 1 public class in 1 java file
class Employee{
int id;
int salary;
String name;
//String data type has S capital
//Just as methpd/function has parameters, Java class has attrubutes to create objects with
new keyword
public void printDetails(){
System.out.println("My id is "+ id);
System.out.println("My name is "+ name);
}
public int getSalary(){
return salary;
}
}
public class cwh_38_custom_class {
public static void main(String[] args) {
System.out.println("This is our First Custom Class");
//Setting attributes
Employee harry = new Employee();
harry.id = 12;
harry.name = "CodeWithHarry";
harry.salary = 12;
Employee Adhitya = new Employee();
Adhitya.id = 1;
Adhitya.name = "M Adhitya";
Adhitya.salary = 100;
//Any real world object = properties + Behavior; similarly
//objects in OOPs = attributes + methods
//Printing the properties/attributes-
System.out.println("Adhitya's id- ");
System.out.print(Adhitya.id);
System.out.println("Adhitya's full name- ");
System.out.println(Adhitya.name);
//Instead of again and again writing like above, we would like to call a method
System.out.println("Adhitya's details using custom method in custom class- ");
Adhitya.printDetails();// as sout in printDetails already, dont write
Adhitya.printDetails() withing sout here
System.out.println(harry.getSalary());
System.out.println(Adhitya.getSalary());
}
}
Output:
This is our First Custom Class
Adhitya's id-
1Adhitya's full name-
M Adhitya
Adhitya's details using custom method in custom class-
My id is 1
My name is M Adhitya
12
100
]
[
Code:
package com.company;
//Problem - Create Employee1 custom class
class Employee1 {
int salary;
String name;
public int getSalary() {
return salary;
}
public String getName() {
return name;
}
public void setName(String n) {
name = n;
}
}
public class cwh_39_ch8_ps {
public static void main(String[] args) {
Employee1 Harry = new Employee1();
Harry.setName("Adhitya");
Harry.salary = 123;
System.out.println(Harry.getName());
System.out.println(Harry.getSalary());
}
}
Output:
Adhitya
123
]
[
Code:
package com.company;
//Problem - Create class CellPhone which prints ringing.. vibrating.. etc.
class CellPhone{
public void ring(){
System.out.println("Ringing...");
}
public void vibrate(){
System.out.println("Vibrating...");
}
public void callFriend (){
System.out.println("calling Aaditya Aryan");
}
}
public class cwh_39_ch8_ps {
public static void main(String[] args) {
CellPhone samsung = new CellPhone();
samsung.callFriend();
samsung.ring();
samsung.vibrate();
}
}
Output:
calling Aaditya Aryan
Ringing...
Vibrating...
]
[
Code:
package com.company;
//Problem- create class square with a initialize its side, calculating area, perimeter, etc
class Square{
int side;
public float area(){
return side*side;
}
public int perimeter(){
return 4*side;
}
}
public class cwh_39_ch8_ps {
public static void main(String[] args) {
Square a = new Square();
a.side = 4;
System.out.println(a.area());
System.out.println(a.perimeter());
}
}
Output:
16.0
16
]
[
Code:
package com.company;
//Problem- create class Tommy capable of hitting, firing, running, etc.
class Tommy{
public void hit(){
System.out.println("Hitting the enemy");
}
public void run(){
System.out.println("Running from Enemy");
}
public void fire(){
System.out.println("Firing the enemy");
}
}
public class cwh_39_ch8_ps {
public static void main(String[] args) {
Tommy player1 = new Tommy();
player1.hit();
player1.run();
player1.fire();
}
}
Output:
Hitting the enemy
Running from Enemy
Firing the enemy
]
[
Code:
package com.company;
class MyEmployee{
private int id;
private String name;
public void setName(String n){
this.name = n;
}
public String getName(){
return name;
}
public void setId(int i){
this.id = i; //this and other keywords here are access modifiers, getters & setters.
}
public int getId(){
return id;
}
}
public class cwh_40_ch9 {
public static void main(String[] args) {
MyEmployee Adhitya = new MyEmployee();
// Adhitya.id = 45;
// Adhitya.name = "Adhi; --> throws an error due to private access modifier
Adhitya.setName("Adhitya");
System.out.println("Adhitya's id after changing is - "+ Adhitya.getId());
System.out.println(Adhitya.getName());
}
}
Output:
Adhitya's id after changing is - 0
Adhitya
]
[
Code:
package com.company;
import java.util.Scanner;
import java.util.Random;
//Rock Paper Scissor Game
public class cwh_ex2_soln {
public static void main(String[] args) {
// 0 for Rock
//1 for Paper
// 2 for Scissor
Scanner sc = new Scanner(System.in);
int userInput = sc.nextInt();
Random random = new Random();
int computerInput = random.nextInt();
if (userInput==computerInput){
System.out.println("Draw");
}
else if ((userInput==0 && computerInput ==2) || (userInput==1 &&computerInput==0) ||
(userInput ==2 && computerInput==1)){
System.out.println("You Win!");
}
else{
System.out.println("Computer Wins");
}
}
}
Output:
1
Computer Wins
]
[
Code:
package com.company;
//Problem - create a class cylinder and use getters and setters to set its radius and height
class Cylinder{
private int radius;
private int height;
//Click the three dots above and choose "code" then click "Generate" then use it to
//generate code like getter and setters - short trick
public int getHeight() {
return height;
}
public void setHeight(int height) {
this.height = height;
}
public int getRadius() {
return radius;
}
public void setRadius(int radius) {
this.radius = radius;
}
}
public class cwh_44_ps09 {
public static void main(String[] args) {
Cylinder myCylinder = new Cylinder();
myCylinder.setHeight(13);
int h = myCylinder.getHeight();
System.out.println(h);
myCylinder.setRadius(3);
System.out.println(myCylinder.getRadius());
}
}
Output:
13
3
]
[
Code:
package com.company;
//Problem - create a class cylinder and use getters and setters to set its radius and height
//with surface area and volume
class Cylinder{
private int radius;
private int height;
//Click the three dots above and choose "code" then click "Generate" then use it to
//generate code like getter and setters - short trick
public int getHeight() {
return height;
}
public void setHeight(int height) {
this.height = height;
}
public int getRadius() {
return radius;
}
public void setRadius(int radius) {
this.radius = radius;
}
public double surfaceArea(){
return 2*3.14*radius*radius + 2*3.14*radius*height;
}
public double volume(){
return 3.14*radius*radius*height;
}
}
public class cwh_44_ps09 {
public static void main(String[] args) {
Cylinder myCylinder = new Cylinder();
myCylinder.setHeight(13);
int h = myCylinder.getHeight();
System.out.println(h);
myCylinder.setRadius(3);
System.out.println(myCylinder.getRadius());
System.out.println(myCylinder.volume());
System.out.println(myCylinder.surfaceArea());
}
}
Output:
13
3
367.38
301.44
]
[
Code:
package com.company;
//Problem - create a class cylinder and use constructors to set its radius and height
//with surface area and volume
class Cylinder{
private int radius;
private int height;
public Cylinder(int radius, int height) {
this.radius = radius;
this.height = height; //Using Constructor
}
//Click the three dots above and choose "code" then click "Generate" then use it to
//generate code like getter and setters - short trick
public int getHeight() {
return height;
}
public void setHeight(int height) {
this.height = height;
}
public int getRadius() {
return radius;
}
public void setRadius(int radius) {
this.radius = radius;
}
public double surfaceArea(){
return 2*Math.PI*radius*radius + 2*3.14*radius*height;
}
public double volume(){
return Math.PI*radius*radius*height; //use Math.PI for accurate value of Pi
}
}
public class cwh_44_ps09 {
public static void main(String[] args) {
Cylinder myCylinder = new Cylinder(12,9);
// myCylinder.setHeight(13);
int h = myCylinder.getHeight();
System.out.println(h);
// myCylinder.setRadius(3);
System.out.println(myCylinder.getRadius());
System.out.println(myCylinder.volume());
System.out.println(myCylinder.surfaceArea());
}
}
Output:
9
12
4071.5040790523717
1583.0186842338603
]
[
Code:
package com.company;
//Problem - overload a constructor used to initialize a rectangle of length 4 and breadth 5
// for using custom parameters
class Rectangle {
private int length;
private int breadth;
public Rectangle(int length, int breadth) {
this.length = length;
this.breadth = breadth;
}
public int getLength() {
return length;
}
public void setLength(int length) {
this.length = length;
}
public int getBreadth() {
return breadth;
}
public void setBreadth(int breadth) {
this.breadth = breadth;
}
}
//Click the three dots above and choose "code" then click "Generate" then use it to
//generate code like getter and setters - short trick
public class cwh_44_ps09 {
public static void main(String[] args) {
Rectangle r = new Rectangle(4,5);
System.out.println(r.getBreadth());
System.out.println(r.getLength());
}
}
Output:
5
4
]
[
Code:
package com.company;
//Problem - create a class Sphere and use getters and setters to print its surface area and
volume
//Click the three dots above and choose "code" then click "Generate" then use it to
//generate code like getter and setters - short trick
class Sphere{
private int radius;
public void setRadius(int r){
radius = r;
}
public int getRadius(){
return radius;
}
public float area(){
return (float) (4*Math.PI*radius*radius);
}
public double volume(){
return (4/3)*Math.PI*radius*radius*radius;
}
}
public class cwh_44_ps09 {
public static void main(String[] args) {
Sphere s = new Sphere();
s.setRadius(5);
System.out.println(s.getRadius());
System.out.println(s.area());
System.out.println(s.volume());
}
}
Output:
5
314.15927
392.69908169872417
]
[
Code:
package com.company;
//Inheritance concept
class Base{
int x;
public int getX() {
return x;
}
public void setX(int x) {
System.out.println("I am in base and I am setting value of X now");
this.x = x;
}
public void printMe(){
System.out.println("I am a constructor");
}
}
//Inheritance uses existing class to create new class in such a way,
// such that the code of previous class is also there behind the screen in current class
class Derived extends Base{
int y;
public int getY() {
return y;
}
public void setY(int y) {
this.y = y;
}
}
public class cwh_45_inheritance {
public static void main(String[] args) {
//Creating an object of base class
Base b = new Base();
b.setX(23);
System.out.println(b.getX());
//Creating an object of derived class in inheritance
Derived d = new Derived();
d.setX(23);
System.out.println(d.getX());
}
}
Output:
I am in base and I am setting value of X now
23
I am in base and I am setting value of X now
23
]
[
Code:
package com.company;
class Base1 {
Base1() { //Constructor is exact copypaste of method, just that its name is same as that of
class
System.out.println("I am a Constructor");
}
Base1(float x) {
System.out.println("I am an Overloaded Constructor with a value of " + x);
}
}
class Derived1 extends Base1 {
Derived1() {
super(0); //To use an argumented Constructed in derived class we use super keyword
System.out.println("I am derived class constructor");
}
}
public class cwh_46_constructors_in_inheritance {
public static void main(String[] args) {
Derived1 d = new Derived1();
}
}
Output:
I am an Overloaded Constructor with a value of 0.0
I am derived class constructor
]
[
Code:
package com.company;
class Base1 {
Base1() { //Constructor is exact copypaste of method, just that its name is same as that of
class
System.out.println("I am a Constructor");
}
Base1(float x) {
System.out.println("I am an Overloaded Constructor with a value of " + x);
}
}
class Derived1 extends Base1 {
Derived1() {
super(0); //To use an argumented Constructed in derived class we use super keyword
System.out.println("I am derived class constructor");
}
Derived1(int x, int y){
super(x);
System.out.println("I am an Overloaded Constructor with a value of " + y);
}
}
public class cwh_46_constructors_in_inheritance {
public static void main(String[] args) {
//Derived1 d = new Derived1();
Derived1 d = new Derived1(4,9);
}
}
Output:
I am an Overloaded Constructor with a value of 4.0
I am an Overloaded Constructor with a value of 9
]
[
Code:
package com.company;
class Base1 {
Base1() { //Constructor is exact copypaste of method, just that its name is same as that of
class
System.out.println("I am a Constructor");
}
Base1(int x) {
System.out.println("I am an Overloaded Constructor with a value of " + x);
}
}
class Derived1 extends Base1 {
Derived1() {
super(0); //To use an argumented Constructed in derived class we use super keyword
System.out.println("I am derived class constructor");
}
Derived1(int x, int y){
super(x);
System.out.println("I am an Overloaded Constructor with a value of " + y);
}
}
class ChildOfDerived1 extends Derived1{
ChildOfDerived1(){
System.out.println("I am a child of derived");
}
ChildOfDerived1(int x, int y, int z){
super(x, y);
System.out.println("I am an overloaded constructor of child of derived with value of z
as "+ z);
}
}
public class cwh_46_constructors_in_inheritance {
public static void main(String[] args) {
//Derived1 d = new Derived1();
// Derived1 d = new Derived1(4,9);
ChildOfDerived1 t = new ChildOfDerived1(3,4,5);
}
}
Output:
I am an Overloaded Constructor with a value of 3
I am an Overloaded Constructor with a value of 4
I am an overloaded constructor of child of derived with value of z as 5
]
[
Code:
package com.company;
import javax.print.Doc;
class EkClass {
int a;
public int getA() {
return a;
}
EkClass(int v) {
this.a = v;
}
public int returnone(){
return 1;
}
}
//super keyword is used to refer to the super class of the current class, and run the
constructor with arguments
class DoC extends EkClass{
DoC(int c){
super(c);
System.out.println("Mai ek constructor hun");
}
}
public class cwh_47_this_super {
public static void main(String[] args) {
EkClass e = new EkClass(65);
DoC d = new DoC(5);
System.out.println(e.getA());
}
}
Output:
Mai ek constructor hun
65
]
[
Code:
package com.company;
//method overriding
class A{
public int a;
public int harry(){
return 4;
}
public void meth2(){
System.out.println("I am method 2 of class A");
}
}
class B extends A{
public void meth2(){
System.out.println("I am method 2 of class B"); //This is method overriding
}// same meth2() of class A in class B so it implements its own meth2()
public void meth3(){
System.out.println("I am method 3 of class B");
}
}
public class cwh_48_method_overriding {
public static void main(String[] args) {
A a = new A();
a.meth2();
B b = new B();
b.meth2();
}
}
Output:
I am method 2 of class A
I am method 2 of class B
]
[
Code:
package com.company;
class Phone{
public void greet(){
System.out.println("Good Morning");
}
public void on(){
System.out.println("Turning on Phone");
}
}
class SmartPhone extends Phone{
public void swagat(){
System.out.println("Aapka swagat hai");
}
@Override
public void on(){
System.out.println("Turning on SmartPhone");
}
}
public class cwh_49_dynamic_method_dispatch {
public static void main(String[] args) {
Phone obj = new SmartPhone();//Superclass reference obj can be equal to sub class object
as here
//SmartPhone obj = new Phone(); // will give error, opposite is not allowed
obj.greet();
obj.on();// It exectutes of the object(smartphone) not of reference(phone)
//This is called dynamic method dispatching
}
}
Output:
Good Morning
Turning on SmartPhone
]
[
Code:
package com.company;
class Phone{
public void showTime(){
System.out.println("Time is 8 am");
}
public void on(){
System.out.println("Turning on Phone");
}
}
class SmartPhone extends Phone{
public void music(){
System.out.println("Playing music...");
}
@Override
public void on(){
System.out.println("Turning on SmartPhone");
}
}
public class cwh_49_dynamic_method_dispatch {
public static void main(String[] args) {
Phone obj = new SmartPhone();//Superclass reference obj can be equal to sub class object
as here
//SmartPhone obj = new Phone(); // will give error, opposite is not allowed
obj.showTime();
obj.on();// It exectutes of the object(smartphone) not of reference(phone)
//This is called dynamic method dispatching
//obj.music(); // is not allowed
}
}
Output:
Time is 8 am
Turning on SmartPhone
]
[
Code:
package com.company;
import java.util.Random;
import java.util.Scanner;
class Game{
public int number;
public int inputNumber;
public int noOfGuesses;
public int getNoOfGuesses() {
return noOfGuesses;
}
public void setNoOfGuesses(int noOfGuesses) {
this.noOfGuesses = noOfGuesses;
}
Game(){
Random rand = new Random();
this.number = rand.nextInt(100);
}
void takeUserInput(){
System.out.println("Guess the number");
Scanner sc = new Scanner(System.in);
inputNumber= sc.nextInt();
}
boolean isCorrectNumber(){
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;
}
}
public class cwh_43_exercise3 {
public static void main(String[] args) {
/* create a class Game which allows user to play "Guess the Number"
game once.Game should have the following methods-
1. Constructor to generate the random number
2. takeUserInput() to take user input of a number
3. isCorrectNumber() i=to check whether entered number is correct
4. getter and setters for no. of guesses
Use properties such as noOfGuesses(int) to get the task done */
Game g = new Game();
boolean b = false;
while(!b) {
g.takeUserInput();
b = g.isCorrectNumber();
System.out.println(b);
}
}
}
Output:
Guess the number
2
Too low...
false
Guess the number
5
Too low...
false
Guess the number
8
True
]
[
Code:
package com.company;
//create a class circle and use inheritance to create another class cylinder from it
class Circle{
Circle(){
System.out.println("I am non parameter of circle");
}
Circle(int r){
System.out.println("I am Circle Parameterized constructor");
this.radius = r;
}
public int radius;
public double area(){
return Math.PI*this.radius*this.radius;
}
}
class Cylinder extends Circle{
public int height;
Cylinder(int r, int h) {
//Super keyword means only super's words will be listened to first, so the
//default constructor will not be run, what super says will be run first
super(r);
System.out.println("I am Cylinder Parameterized constructor");
this.height=h;
}
public double volume(){
return Math.PI*this.radius*this.radius*this.height;
}
}
public class cwh_52_chap10ps {
public static void main(String[] args) {
Circle obj = new Circle(12);
System.out.println("Area is: ");
System.out.println(obj.area());
Cylinder obj2 = new Cylinder(2,3);
System.out.println("Volume is: ");
System.out.println(obj2.volume());
}
}
Output:
I am Circle Parameterized constructor
Area is:
452.3893421169302
I am Circle Parameterized constructor
I am Cylinder Parameterized constructor
Volume is:
37.69911184307752
]
[
Code:
package com.company;
//Abstract class is a class jiski sahayata lekar aur classes aap bana te ho
//Abstract class ek class hota nhi hai, lekin vo ek zariya hai, Child2 jaise concrete class
banane ka
// Abstract classes cant have objects
//Analogy - Parent2 class is saying to his Child2 and Child3 classes, bacchon, please use
greet() abstract
//anyway you want or you yourself become a standard that is parent
abstract class Parent2{ // 1 abstract method makes whole class abstract.
//Must declare the whole class as abstract using abstract keyword
public Parent2(){
System.out.println("Mai base2 ka constructor hun");
}
public void sayHello(){
System.out.println("Hello");
}
abstract public void greet();
abstract public void greet2();
}
class Child2 extends Parent2{
@Override
public void greet(){
System.out.println("Good Morning");
}
@Override
public void greet2(){
System.out.println("Good Afternoon");
}
}
abstract class Child3 extends Parent2{
public void th(){
System.out.println("I am Good");
}
}
public class cwh_53_abstract {
public static void main(String[] args) {
Child2 c = new Child2();
// Parent2 p = new Parent2(); ---- Error
// Child3 c3 = new Child3(); ---- Error
}
}
Output:
Mai base2 ka constructor hun
]
[
Code:
package com.company;
interface Bicycle{
int a = 45; // Attribute or property
void applyBrake(int decrement);
void speedUp(int increment);
}
interface HornBicycle{
public int b = 45;
void blowHornK3g();
void blowHornmhn();
}
class AvonCycle implements Bicycle,HornBicycle{
public int b = 5;
void blowHorn(){
System.out.println("Pee pee poo poo");
}
//ALWAYS the methods of interface should have public access modifiers
public void applyBrake(int decrement){
System.out.println("Applying brake...");
}
public void speedUp(int increment){
System.out.println("Speeding Up...");
}
public void blowHornK3g(){
System.out.println("Kabhi kushi kabhi gum pee pee pee pee");
}
public void blowHornmhn(){
System.out.println("Mai hun na po po po po");
}
}
public class cwh_54_Interfaces {
public static void main(String[] args) {
AvonCycle cycleAdhi = new AvonCycle();
cycleAdhi.applyBrake(1);
//You can create property in Interfaces
System.out.println(cycleAdhi.a);
//You can not modify the properties in Interfaces as they are final
// cycleAdhi.a = 454; ---> gives error
cycleAdhi.blowHornK3g();
cycleAdhi.blowHornmhn();
System.out.println(cycleAdhi.b);
}
}
Output:
Applying brake...
45
Kabhi kushi kabhi gum pee pee pee pee
Mai hun na po po po po
5
]
[
Code:
package com.company;
interface MyCamera {
void takeSnap();
void recordVideo();
private void greet(){
System.out.println("Good Morning");
}
default void record4KVideo() {
greet(); // private methods in interface cannot be directly used by class but, using
default methods
// we can use the private method
System.out.println("Recording 4K...");
} //default was introduced as if we add 1 abstract method in interface, all existin classes
implementing
//the interface will fail, and we have to correct all of them, so we add
//default method so that we dont need to edit ALL existing classes using the interface
}
interface MyWifi{
String [] getNetworks();
void connectToNetwork(String network);
}
class MyCellPhone{
void callnumber(int phoneNumber){
System.out.println("Calling"+ phoneNumber);
}
void pickCall(){
System.out.println("Connecting...");
}
public void takeSnap(){
System.out.println("Taking snap");
}
}
class MySmartPhone extends MyCellPhone implements MyWifi, MyCamera{
public void takeSnap(){
System.out.println("Taking snap");
}
public void recordVideo(){
System.out.println("Taking snap");
}
@Override
public void record4KVideo(){
System.out.println("Taking Snap and recording 4K Video"); // can comment this override
code to get another output
}
public String [] getNetworks() {
System.out.println("Getting List of Networks");
String [] networkList = {"Adhi", "Jake"};
return networkList;
}
public void connectToNetwork(String network){
System.out.println("Connecting.."+ network);
}
}
public class cwh_57_default_methods {
public static void main(String[] args) {
MySmartPhone ms = new MySmartPhone();
ms.record4KVideo(); //Default method
String [] ar = ms.getNetworks();
for (String item : ar){
System.out.println(item);
}
}
}
//Two types of methods - static methods and default methods
// Static method is not associated with object, it is only associated with class or interface
Output:
Taking Snap and recording 4K Video
Getting List of Networks
Adhi
Jake
]
[
Code:
package com.company;
//To follow the Do Not Repeat Yourself(DRY) principle, we follow Inheritance in Interfaces
interface sampleInterface{
void meth1();
void meth2();
}
interface childSampleInterface extends sampleInterface{
void meth3();
void meth4();
}
class MySampleClass implements childSampleInterface{
public void meth1(){
System.out.println("meth1");
}
public void meth2(){
System.out.println("meth2");
}
public void meth3(){
System.out.println("meth3");
}
public void meth4(){
System.out.println("meth4");
}
}
public class cwh_58_inheritance_interfaces {
public static void main(String[] args) {
MySampleClass obj = new MySampleClass();
obj.meth1();
obj.meth2();
obj.meth3();
obj.meth4();
}
}
Output:
meth1
meth2
meth3
meth4
]
[
Code:
package com.company;
//Polymorphism
interface MyCamera2{
void takeSnap();
void recordVideo();
private void greet(){
System.out.println("Good Morning");
}
default void record4KVideo() {
greet(); // private methods in interface cannot be directly used by class but, using
default methods
// we can use the private method
System.out.println("Recording 4K...");
} //default was introduced as if we add 1 abstract method in interface, all existin classes
implementing
//the interface will fail, and we have to correct all of them, so we add
//default method so that we dont need to edit ALL existing classes using the interface
}
interface MyWifi2{
String [] getNetworks();
void connectToNetwork(String network);
}
class MyCellPhone2{
void callnumber(int phoneNumber){
System.out.println("Calling"+ phoneNumber);
}
void pickCall(){
System.out.println("Connecting...");
}
public void takeSnap(){
System.out.println("Taking snap");
}
}
class MySmartPhone2 extends MyCellPhone2 implements MyWifi2, MyCamera2{
public void takeSnap(){
System.out.println("Taking snap");
}
public void recordVideo(){
System.out.println("Taking snap");
}
@Override
public void record4KVideo(){
System.out.println("Taking Snap and recording 4K Video"); // can comment this override
code to get another output
}
public String [] getNetworks() {
System.out.println("Getting List of Networks");
String [] networkList = {"Adhi", "Jake"};
return networkList;
}
public void connectToNetwork(String network){
System.out.println("Connecting.."+ network);
}
}
public class cwh_59_polymorphism {
public static void main(String[] args) {
MyCamera2 cam1 = new MySmartPhone2(); //This is a SmartPhone but use it as a Camera
//cam1.getNetworks(); ----> not allowed
cam1.record4KVideo();
MySmartPhone2 s = new MySmartPhone2();
s.getNetworks();
s.recordVideo();
s.callnumber(23453);
}
}
Output:
Taking Snap and recording 4K Video
Getting List of Networks
Taking snap
Calling23453
]
[
Code:
package com.company;
//create an abstract class Pen with abstract methods write() and refill() as abstract methods
//create a concrete class FountainPen with additional method changeNib()
abstract class Pen{
abstract void write();
abstract void refill();
}
class FountainPen extends Pen{
void write(){
System.out.println("Writing");
}
void refill(){
System.out.println("Refill");
}
void changeNib(){
System.out.println("Changing the Nib");
}
}
public class cwh_60_ch11ps {
public static void main(String[] args) {
FountainPen pen = new FountainPen();
pen.changeNib();
}
}
Output:
Changing the Nib
]
[
Code:
package com.company;
//create class Monkey with jump() and bite() methods. Create a class Human which inherits this
class Monkey
//and implements BasicAnimal interface with eat() and sleep() methods
class Monkey{
void jump(){
System.out.println("Jumping...");
}
void bite(){
System.out.println("Biting...");
}
}
interface BasicAnimal{
void eat();
void sleep();
}
class Human extends Monkey implements BasicAnimal{
void speak(){
System.out.println("Hello !");
}
public void eat(){
System.out.println("Eating...");
}
public void sleep(){
System.out.println("Sleeping...");
}
}
public class cwh_60_ch11ps {
public static void main(String[] args) {
Human Adhi = new Human();
Adhi.eat();
Adhi.sleep();
Adhi.speak();
Adhi.bite();
Adhi.jump();
}
}
Output:
Eating...
Sleeping...
Hello !
Biting...
Jumping...
]
[
Code:
package com.company;
//create class Monkey with jump() and bite() methods. Create a class Human which inherits this
class Monkey
//and implements BasicAnimal interface with eat() and sleep() methods
// And demonstrate polymorphism
class Monkey{
void jump(){
System.out.println("Jumping...");
}
void bite(){
System.out.println("Biting...");
}
}
interface BasicAnimal{
void eat();
void sleep();
}
class Human extends Monkey implements BasicAnimal{
void speak(){
System.out.println("Hello !");
}
public void eat(){
System.out.println("Eating...");
}
public void sleep(){
System.out.println("Sleeping...");
}
}
public class cwh_60_ch11ps {
public static void main(String[] args) {
Human Adhi = new Human();
Adhi.eat();
Adhi.sleep();
Adhi.speak();
Adhi.bite();
Adhi.jump();
Monkey m1 = new Human();
// m1.speak(); // ---> gives error, cannot use speak() method as
// reference is Monkey which does not have speak() method
m1.jump();
m1.bite();
BasicAnimal lovish = new Human();
//lovish.speak(); ---> gives error and this demonstrates polymorphism
}
}
Output:
Eating...
Sleeping...
Hello !
Biting...
Jumping...
Jumping...
Biting...
]
[
Code:
package com.company;
class Library{
String []books;
int no_of_books = 0;
Library(){
this.books = new String[100];
this.no_of_books=0;
}
void addBook(String book){
this.books[no_of_books]= book;
no_of_books++;
System.out.println(book + " has been added!");
}
void showAvailableBooks(){
System.out.println("Available Books are...");
for(String item : this.books){
if(item == null){
continue;
}
System.out.println("*" + item);
}
}
void issueBook(String book){
for (int i =0; i<this.books.length; i++){
if(this.books[i].equals(book)){
System.out.println("This book has been issued!");
this.books[i]= null;
return;
}
}
System.out.println("This book does not exist!");
}
void returnBook(String book){
addBook(book);
}
}
public class cwh_51_exercise4 {
public static void main(String[] args) {
//You have to implement a class library using Java Class Library
//Methods: issueBook, returnBook, showAvailableBooks
//Properties: array to store the available books
//Array to store issued books
Library centralLibrary = new Library();
centralLibrary.addBook("Think and Grow Rich!");
centralLibrary.addBook("Ikigai");
centralLibrary.addBook("Atomic Habits");
centralLibrary.showAvailableBooks();
centralLibrary.issueBook("Atomic Habits");
centralLibrary.showAvailableBooks();;
centralLibrary.returnBook("Atomic Habits");
centralLibrary.showAvailableBooks();
}
}
Output:
Think and Grow Rich! has been added!
Ikigai has been added!
Atomic Habits has been added!
Available Books are...
*Think and Grow Rich!
*Ikigai
*Atomic Habits
This book has been issued!
Available Books are...
*Think and Grow Rich!
*Ikigai
Atomic Habits has been added!
Available Books are...
*Think and Grow Rich!
*Ikigai
*Atomic Habits
]
[
Code:
package com.company;
//Access modifiers access in same class illustration
class C1{
public int x = 5;
protected int y = 45;
int z = 7;
private int a = 73;
public void meth1(){
System.out.println(x);
System.out.println(y);
System.out.println(z);
System.out.println(a);
}
}
public class cwh_66_access_modifiers {
public static void main(String[] args) {
C1 c = new C1();
c.meth1();
}
}
Output:
5
45
7
73
]
[
Code:
package com.company;
//Access modifiers access in same package illustration
class C1{
public int x = 5;
protected int y = 45;
int z = 7;
private int a = 73;
public void meth1(){
System.out.println(x);
System.out.println(y);
System.out.println(z);
System.out.println(a);
}
}
public class cwh_66_access_modifiers {
public static void main(String[] args) {
C1 c = new C1();
System.out.println(c.x);
System.out.println(c.y);
System.out.println(c.z);
//System.out.println(c.a); --> gives error as private access
}
}
Output:
5
45
7
]
[
Code:
package com.company;
//Difference b/w concurrency and parallelism is similar to difference b/w parameters and
arguments
// Concurrency means, you are managing multiple tasks overall, but at a time you are doing only
one task
//Parallelism means actually both tasks are happening together simultaneously
//Multithreading in java follows concurrency
//We use Threads to achieve multitasking within a process
class MyThread1 extends Thread{
@Override
public void run(){
int i = 0;
while(i<5){
System.out.println("My thread is running");
System.out.println("I am happy!");
i++;
}
}
}
class MyThread2 extends Thread{
@Override
public void run(){
int i = 0;
while(i<5){
System.out.println("Thread2 is good");
System.out.println("I am sad");
i++;
}
}
}
public class cwh_70 {
public static void main(String[] args) {
MyThread1 t1 = new MyThread1();
MyThread2 t2 = new MyThread2();
t1.start();
t2.start();// start() is method to run threads
}
}
Output:
My thread is running
Thread2 is good
I am happy!
My thread is running
I am happy!
My thread is running
I am happy!
My thread is running
I am happy!
My thread is running
I am happy!
I am sad
Thread2 is good
I am sad
Thread2 is good
I am sad
Thread2 is good
I am sad
Thread2 is good
I am sad
]
[
Code:
package com.company;
//Runnable is an in built interface in Thread
class MyThreadRunnable1 implements Runnable{
public void run(){
System.out.println("I am a thread1 not a threat1");
}
}
class MyThreadRunnable2 implements Runnable{
public void run(){
System.out.println("I am a thread2 not a threat2");
}
}
public class cwh_71_runnable {
public static void main(String[] args) {
MyThreadRunnable1 bullet1 = new MyThreadRunnable1();
MyThreadRunnable2 bullet2 = new MyThreadRunnable2();
Thread gun1 = new Thread(bullet1);
Thread gun2 = new Thread(bullet2);
gun1.start();
gun2.start();
}
}
Output:
I am a thread1 not a threat1
I am a thread2 not a threat2
]
[
Code:
package com.company;
//Thread is a class
//Refer to notes for Constructors in java types
//start() is for starting Thread
class MyThr extends Thread{
public MyThr(String name){
super(name); // as there is already a constructor in Thread that uses name
}
public void run(){
int i = 34;
System.out.println("Thank you");
}
}
public class cwh_73_thread_constructor {
public static void main(String[] args) {
MyThr t = new MyThr("Adhi");
MyThr t2 = new MyThr("M");
t.start();
System.out.println("The id of this thread is "+ t.getId());
System.out.println("The name of the thread is "+ t.getName());
System.out.println("The id of t2 is "+ t.getId());
System.out.println("The name of t2 is "+ t.getName());
}
}
Output:
The id of this thread is 20
The name of the thread is Adhi
The id of t2 is 20
The name of t2 is Adhi
Thank you
]
[
Code:
package com.company;
class MyThr1 extends Thread{
public MyThr1(String name){
super(name); // as there is already a constructor in Thread that uses name
}
public void run(){
int i = 34;
System.out.println("Thank you " + this.getName());
}
}
public class cwh_74_thread_priorities {
public static void main(String[] args) {
MyThr1 t1 = new MyThr1("Adhi1");
MyThr1 t2 = new MyThr1("Adhi2");
MyThr1 t3 = new MyThr1("Adhi3");
MyThr1 t4 = new MyThr1("Adhi4");
MyThr1 t5 = new MyThr1("Adhi5");
t1.start();
t2.start();
t3.start();
t4.start();
t5.start();
}
}
Output:
Thank you Adhi1
Thank you Adhi2
Thank you Adhi3
Thank you Adhi4
Thank you Adhi5
]
[
Code:
package com.company;
//Thread Priorities
class MyThr1 extends Thread{
public MyThr1(String name){
super(name); // as there is already a constructor in Thread that uses name
}
public void run(){
int i = 34;
System.out.println("Thank you " + this.getName());
}
}
public class cwh_74_thread_priorities {
public static void main(String[] args) {
MyThr1 t1 = new MyThr1("Adhi1");
MyThr1 t2 = new MyThr1("Adhi2");
MyThr1 t3 = new MyThr1("Adhi3");
MyThr1 t4 = new MyThr1("Adhi4");
MyThr1 t5 = new MyThr1("Adhi5");
t5.setPriority(Thread.MAX_PRIORITY); //max priority
t1.setPriority(Thread.MIN_PRIORITY); //min priority
t1.start();
t2.start();
t3.start();
t4.start();
t5.start();
}
}
Output:
Thank you Adhi5
Thank you Adhi2
Thank you Adhi3
Thank you Adhi4
Thank you Adhi1
]
[
Code:
package com.company;
class MyNewThr1 extends Thread{
public void run(){
int i = 0;
while(i<8){
System.out.println("Thank you");
i++;
}
}
}
class MyNewThr2 extends Thread{
public void run(){
int j = 0;
while(j<8){
System.out.println("Thank you2");
j++;
}
}
}
public class cwh_75_thread_method {
public static void main(String[] args) {
MyNewThr1 t1 = new MyNewThr1();
MyNewThr2 t2 = new MyNewThr2();
t1.start();
try{ //put it in try-catch block
t1.join(); //Join can be used if you want it like till t1 doesnt end, t2 doesnt
start
}
catch(Exception e){
System.out.println(e);
}
t2.start();
}
}
Output:
Thank you
Thank you
Thank you
Thank you
Thank you
Thank you
Thank you
Thank you
Thank you2
Thank you2
Thank you2
Thank you2
Thank you2
Thank you2
Thank you2
Thank you2
]
[
Code:
package com.company;
//Thread Method - Interrupted Method
class MyNewThr1 extends Thread{
public void run(){
int i = 0;
while(i<8){
System.out.println("Thank you");
try {
Thread.sleep(8);
} catch (InterruptedException e) { //Interrupted Method
throw new RuntimeException(e);
}
i++;
}
}
}
class MyNewThr2 extends Thread{
public void run(){
int j = 0;
while(j<8){
System.out.println("Thank you2");
j++;
}
}
}
public class cwh_75_thread_method {
public static void main(String[] args) {
MyNewThr1 t1 = new MyNewThr1();
MyNewThr2 t2 = new MyNewThr2();
t1.start();
t2.start();
}
}
Output:
Thank you
Thank you2
Thank you2
Thank you2
Thank you2
Thank you2
Thank you2
Thank you2
Thank you2
Thank you
Thank you
Thank you
Thank you
Thank you
Thank you
Thank you
]
[
Code:
package com.company;
//write a program to print "good morning" and "welcome" continuously till an end point in Java
using Threads
class Practice13a extends Thread{
public void run(){
int i = 0;
while(i<8){
System.out.println("good morning");
i++;
}
}
}
class Practice13b extends Thread{
public void run(){
int i = 0;
while(i<8){
System.out.println("Welcome");
i++;
}
}
}
public class cwh_76_practice13 {
public static void main(String[] args) {
Practice13a p1 = new Practice13a();
Practice13b p2 = new Practice13b();
p1.start();
p2.start();
}
}
Output:
good morning
good morning
good morning
good morning
good morning
good morning
good morning
good morning
Welcome
Welcome
Welcome
Welcome
Welcome
Welcome
Welcome
Welcome
]
[
Code:
package com.company;
//write a program to print "good morning" and "welcome" continuously till an end point in Java
using Threads
//Then add sleep method to this, and delay the execution by 200ms of the Welcome thread
class Practice13a extends Thread{
public void run(){
int i = 0;
while(i<8){
System.out.println("good morning");
i++;
}
}
}
class Practice13b extends Thread{
public void run(){
int i = 0;
while(i<8){
try {
Thread.sleep(200);
}
catch (InterruptedException e) {
throw new RuntimeException(e);
}
System.out.println("Welcome");
i++;
}
}
}
public class cwh_76_practice13 {
public static void main(String[] args) {
Practice13a p1 = new Practice13a();
Practice13b p2 = new Practice13b();
p1.start();
p2.start();
}
}
Output:
good morning
good morning
good morning
good morning
good morning
good morning
good morning
good morning
Welcome
Welcome
Welcome
Welcome
Welcome
Welcome
Welcome
Welcome
]
[
Code:
package com.company;
//write a program to print "good morning" and "welcome" continuously till an end point in Java
using Threads
//Then add sleep method to this, and delay the execution by 200ms of the Welcome thread
//Then Demonstrate setPriority() and getPriority() methods in Java
class Practice13a extends Thread{
public void run(){
int i = 0;
while(i<8){
System.out.println("good morning");
i++;
}
}
}
class Practice13b extends Thread{
public void run(){
int i = 0;
while(i<8){
try {
Thread.sleep(200);
}
catch (InterruptedException e) {
throw new RuntimeException(e);
}
System.out.println("Welcome");
i++;
}
}
}
public class cwh_76_practice13 {
public static void main(String[] args) {
Practice13a p1 = new Practice13a();
Practice13b p2 = new Practice13b();
p1.setPriority(6);
p2.setPriority(9);
System.out.println(p1.getPriority());
System.out.println(p2.getPriority());
//p1.start();
//p2.start();
//If setPriority() is not done, they have normal priority equal
//NORM_PRIORITY value is 5
}
}
Output:
6
9
]
[
Code:
package com.company;
//How do you get the state of a thread in java?
class Practice13a extends Thread{
public void run(){
int i = 0;
while(i<8){
System.out.println("good morning");
i++;
}
}
}
class Practice13b extends Thread{
public void run(){
int i = 0;
/* while(i<8){
try {
Thread.sleep(200);
}
catch (InterruptedException e) {
throw new RuntimeException(e);
}
System.out.println("Welcome");
i++;
}*/
}
}
public class cwh_76_practice13 {
public static void main(String[] args) {
Practice13a p1 = new Practice13a();
Practice13b p2 = new Practice13b();
p1.setPriority(6);
p2.setPriority(9);
System.out.println(p1.getPriority());
System.out.println(p2.getPriority());
//p1.start();
System.out.println(p2.getState());
p2.start();
System.out.println(p2.getState());
//getState() gives the state of the thread
}
}
Output:
6
9
NEW
RUNNABLE
]
[
Code:
package com.company;
//How do you get reference to the current thread in Java? - using currentThread()
class Practice13a extends Thread{
public void run(){
int i = 0;
while(i<8){
System.out.println("good morning");
i++;
}
}
}
class Practice13b extends Thread{
public void run(){
int i = 0;
while(i<8){
try {
Thread.sleep(200);
}
catch (InterruptedException e) {
throw new RuntimeException(e);
}
System.out.println("Welcome");
i++;
}
}
}
public class cwh_76_practice13 {
public static void main(String[] args) {
Practice13a p1 = new Practice13a();
Practice13b p2 = new Practice13b();
p1.setPriority(6);
p2.setPriority(9);
System.out.println(p1.getPriority());
System.out.println(p2.getPriority());
//p1.start();
// System.out.println(p2.getState());
p2.start();
//System.out.println(p2.getState());
System.out.println(Thread.currentThread());
}
}
Output:
6
9
Thread[#1,main,5,main]
Welcome
Welcome
Welcome
Welcome
Welcome
Welcome
Welcome
Welcome
]
[
Code:
package com.company;
public class cwh_78_errors {
public static void main(String[] args) {
//Write a program to print all prime numbers between 1 to 10
System.out.println(2);
for(int i=1; i<5; i++){
System.out.println(2*i+1);
//this is logical error as it prints odd numbers and not prime numbers
}
}
}
Output:
2
3
5
7
9
]
[
Code:
package com.company;
//Arithmetic exception example
public class cwh_80_try {
public static void main(String[] args) {
int a = 6000;
int b = 0;
int c = a/b;
System.out.println("the result is "+ c);
}
}
Output:
Exception in thread "main" java.lang.ArithmeticException: / by zero
at com.company.cwh_80_try.main(cwh_80_try.java:7)
]
[
Code:
package com.company;
//Solving Arithmetic Exception of division by zero using Try catch block
public class cwh_80_try {
public static void main(String[] args) {
int a = 6000;
int b = 0;
try{
int c = a/b;
System.out.println("the result is "+ c);
}catch(Exception e){
System.out.println("We couldnt divide because of ");
System.out.println(e);
}
}
}
Output:
We couldnt divide because of
java.lang.ArithmeticException: / by zero
]
[
Code:
package com.company;
//How to hancle specific exceptions.
//Handling specific type of exceptions
import java.util.Scanner;
public class cwh_81 {
public static void main(String[] args) {
int [] marks = new int[3];
marks[0] = 7;
marks[1] = 56;
marks[2] = 6;
Scanner sc = new Scanner(System.in);
System.out.println("Enter the array index: ");
int ind = sc.nextInt();
System.out.println("Enter the number with which you want to divide the value with: ");
int number = sc.nextInt();
try{
System.out.println("The value of the value at index entered is : "+ marks[ind]);
System.out.println("The array of array-value/number is : "+ marks[ind]/number);
}catch(Exception e){
System.out.println("Some Exception error occurred!");
System.out.println(e);
}
}
}
Output:
Enter the array index:
1
Enter the number with which you want to divide the value with:
23
The value of the value at index entered is : 56
The array of array-value/number is : 2
]
[
Code:
package com.company;
//How to hancle specific exceptions.
//Handling specific type of exceptions
import java.util.Scanner;
public class cwh_81 {
public static void main(String[] args) {
int [] marks = new int[3];
marks[0] = 7;
marks[1] = 56;
marks[2] = 6;
Scanner sc = new Scanner(System.in);
System.out.println("Enter the array index: ");
int ind = sc.nextInt();
System.out.println("Enter the number with which you want to divide the value with: ");
int number = sc.nextInt();
try{
System.out.println("The value of the value at index entered is : "+ marks[ind]);
System.out.println("The array of array-value/number is : "+ marks[ind]/number);
}catch(ArithmeticException e){
System.out.println("Some Exception error occurred!");
System.out.println(e);
}catch(ArrayIndexOutOfBoundsException e){
System.out.println("Some Exception error occurred!");
System.out.println(e);
}catch(Exception e){
System.out.println("Some Exception error occurred!");
System.out.println(e);
}
}
}
Output:
Enter the array index:
4
Enter the number with which you want to divide the value with:
2
Some Exception error occurred!
java.lang.ArrayIndexOutOfBoundsException: Index 4 out of bounds for length 3
]
[
Code:
package com.company;
//nested try catch have levels
public class cwh_82_nested_try_catch {
public static void main(String[] args) {
int [] marks = new int[5];
marks[0] = 7;
marks[1] = 56;
marks[2] = 6;
try{
System.out.println("We are in try level 1");
try{
System.out.println(marks[9]);
}catch(ArrayIndexOutOfBoundsException e){
System.out.println("Sorry this index does not exist");
System.out.println("Exception in level 2");
}
}catch(Exception e) {
System.out.println("Exception in level 1");
}
}
}
Output:
We are in try level 1
Sorry this index does not exist
Exception in level 2
]
[
Code:
package com.company;
//nested try catch have levels
import java.util.Scanner;
public class cwh_82_nested_try_catch {
public static void main(String[] args) {
int [] marks = new int[5];
marks[0] = 7;
marks[1] = 56;
marks[2] = 6;
Scanner sc = new Scanner(System.in);
System.out.println("Enter the value of index: ");
int ind = sc.nextInt();
try{
System.out.println("We are in try level 1");
try{
System.out.println(marks[ind]);
}
catch(ArrayIndexOutOfBoundsException e){
System.out.println("Sorry this index does not exist");
System.out.println("Exception in level 2");
}
}
catch(Exception e) {
System.out.println("Exception in level 1");
}
}
}
Output:
Enter the value of index:
1
We are in try level 1
56
]
[
Code:
package com.company;
//nested try catch have levels
import org.w3c.dom.ls.LSOutput;
import java.util.Scanner;
public class cwh_82_nested_try_catch {
public static void main(String[] args) {
int[] marks = new int[5];
marks[0] = 7;
marks[1] = 56;
marks[2] = 6;
Scanner sc = new Scanner(System.in);
boolean flag = true;
while (flag) {
System.out.println("Enter the value of index: ");
int ind = sc.nextInt();
try {
System.out.println("We are in try level 1");
try {
System.out.println(marks[ind]);
flag = false;
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Sorry this index does not exist");
System.out.println("Exception in level 2");
}
} catch (Exception e) {
System.out.println("Exception in level 1");
}
}
System.out.println("Thank you for using the program");
}
}
Output:
Enter the value of index:
1
We are in try level 1
56
Thank you for using the program
]
[
Code:
package com.company;
import java.util.Scanner;
class MyException extends Exception{
@Override
public String toString(){
return super.toString() + " I am toString()";
}
public String getMessage(){
return super.getMessage() + " I am getMessage()";
}
}
public class cwh_83_exception_class {
public static void main(String[] args) throws MyException {
int a;
Scanner sc = new Scanner(System.in);
System.out.println("enter a: ");
a = sc.nextInt();
if (a<9){
try {
throw new MyException();
}catch(Exception e){
System.out.println(e.getMessage());
}
}
}
}
Output:
enter a:
4
null I am getMessage()
]
[
Code:
package com.company;
//Harry made a function. Shivam tries to use it. Harry can warn shivam that there is a
possibilty of exception
//Shivam should accrodingly create a try catch block
public class cwh_84_throw_throws {
public static int divide(int a, int b) throws ArithmeticException{
//Made by Harry
int result = a/b;
return result;
}
public static void main(String[] args) {
//Shivam - uses divide function created by Harry
try{
int c = divide(6, 0);
System.out.println(c);
}
catch(Exception e){
System.out.println("Exception");
}
}
}
Output:
Exception
]
[
Code:
package com.company;
import java.util.Scanner;
class MyException extends Exception{
@Override
public String toString(){
return" I am toString()";
}
public String getMessage(){
return " I am getMessage()";
}
}
public class cwh_83_exception_class {
public static void main(String[] args) throws MyException {
int a;
Scanner sc = new Scanner(System.in);
System.out.println("enter a: ");
a = sc.nextInt();
if (a<9){
try {
throw new ArithmeticException("This is an Exception") ;
}catch(Exception e){
System.out.println(e.getMessage());
System.out.println("Finished");
}
System.out.println("Yes Finished");
}
}
}
Output:
enter a:
3
This is an Exception
Finished
Yes Finished
]
[
Code:
package com.company;
//code in finally block is always executed no matter what even if it is an exception
public class cwh_85_finally {
public static void main(String[] args) {
try{
int a = 5;
int b = 0;
int c = a/b;
}catch(Exception e){
System.out.println(e);
}
finally {
System.out.println("This is the end of program");
}
}
}
Output:
java.lang.ArithmeticException: / by zero
This is the end of program
]
[
Code:
package com.company;
//code in finally block is always executed no matter what even if it is an exception
public class cwh_85_finally {
public static int greet() {
try {
int a = 50;
int b = 2;
int c = a / b;
return c;
} catch (Exception e) {
System.out.println(e);
} finally {
System.out.println("This is the end of program");
}
return 0;
}
public static void main(String[] args) {
int k = greet();
System.out.println(k);
}
}
Output:
This is the end of program
25
]
[
Code:
package com.company;
//code in finally block is always executed no matter what even if it is an exception
public class cwh_85_finally {
public static int greet() {
try {
int a = 50;
int b = 10;
int c = a / b;
return c;
} catch (Exception e) {
System.out.println(e);
} finally {
System.out.println("Cleaning up resources... This is the end of program");
}
return 0;
}
public static void main(String[] args) {
int k = greet();
System.out.println(k);
}
}
Output:
Cleaning up resources... This is the end of program
5
]
[
Code:
package com.company;
//code in finally block is always executed no matter what even if it is an exception
public class cwh_85_finally {
public static int greet() {
try {
int a = 50;
int b = 10;
int c = a / b;
return c;
} catch (Exception e) {
System.out.println(e);
} finally {
System.out.println("Cleaning up resources... This is the end of program");
}
return 0;
}
public static void main(String[] args) {
int k = greet();
System.out.println(k);
int a = 7;
int b = 0;
while(true){
try{
System.out.println(a/b);
}catch(Exception e){
System.out.println(e);
break;
}
finally {
System.out.println("I am finally value for b = " + b);
}
} b--;
}
}
Output:
Cleaning up resources... This is the end of program
5
java.lang.ArithmeticException: / by zero
I am finally value for b = 0
]
[
Code:
package com.company;
//code in finally block is always executed no matter what even if it is an exception
public class cwh_85_finally {
public static int greet() {
try {
int a = 50;
int b = 10;
int c = a / b;
return c;
} catch (Exception e) {
System.out.println(e);
} finally {
System.out.println("Cleaning up resources... This is the end of program");
}
return 0;
}
public static void main(String[] args) {
int k = greet();
System.out.println(k);
int a = 7;
int b = 0;
while(true){
try{
System.out.println(a/b);
}catch(Exception e){
System.out.println(e);
break;
}
finally {
System.out.println("I am finally value for b = " + b);
}
} b--;
try{
System.out.println(50/10);
}finally{
System.out.println("Yes this is final");
}
}
}
Output:
Cleaning up resources... This is the end of program
5
java.lang.ArithmeticException: / by zero
I am finally value for b = 0
5
Yes this is final
]
[
Code:
package com.company;
//Problem - demonstrate syntax error and logical error and runtime error
public class cwh_86_ps14 {
public static void main(String[] args) {
// Syntax error - int a = 7
int age = 78;
int year_born = 2000 - 78; //Logical error
// Runtime error - System.out.println(6/0);
System.out.println("SOLVED");
}
}
Output:
SOLVED
]
[
Code:
package com.company;
//Problem - write a Java program that prints "HaHa" during Arithmetic exception and "HeHe" durig
//Illegal Argument exception
public class cwh_86_ps14 {
public static void main(String[] args) {
try{
int a =666/9;
}
catch(IllegalArgumentException e){
System.out.println("HeHe");
}
catch(ArithmeticException e){
System.out.println("HaHa");
}
System.out.println("Finished");
}
}
Output:
Finished
]
[
Code:
package com.company;
//Problem - write a program that allows you to keep accessing the array until a valid index is
given
// if max retries exceed 5 then print error
import java.util.Scanner;
public class cwh_86_ps14 {
public static void main(String[] args) {
boolean flag = true;
int [] marks = new int[3];
marks[0] = 7;
marks[1] = 56;
marks[2] = 6;
Scanner sc = new Scanner(System.in);
int index;
int i = 0;
while(flag && i<5){
try{
System.out.println("Enter index ");
index = sc.nextInt();
System.out.println("The value of marks[index] is " + marks[index]);
i++;
break;
}catch(Exception e){
System.out.println("Invalid Index");
}
}
}
}
Output:
Enter index
3
Invalid Index
Enter index
2
The value of marks[index] is 6
]
[
Code:
package com.company;
// ArrayList, TreeSet, Set are all part of Collection Framework
import java.util.ArrayList;
import java.util.Set;
import java.util.TreeSet;
public class cwh_89_collections {
public static void main(String[] args) {
// ArrayList
// Set
// TreeSet
System.out.println("Done");
}
}
Output:
Done
]
[
Code:
package com.company;
//ArrayList - Advanced Java
// ArrayList can be resized, can we start inserting from a particular index,
// we can do things we wont be able to do with normal array
import java.lang.reflect.Array;
import java.util.*;
public class cwh_91_arraylist {
public static void main(String[] args) {
ArrayList<Integer> l1 = new ArrayList<>();
l1.add(6);
l1.add(7);
l1.add(4);
l1.add(6);
l1.add(5);
for(int i=0; i<l1.size(); i++){
System.out.println(l1.get(i)); //get() method is used to get ith element from
arraylist
}
}
}
Output:
6
7
4
6
5
]
[
Code:
package com.company;
//ArrayList - Advanced Java
// ArrayList can be resized, can we start inserting from a particular index,
// we can do things we wont be able to do with normal array
import java.lang.reflect.Array;
import java.util.*;
public class cwh_91_arraylist {
public static void main(String[] args) {
ArrayList<Integer> l1 = new ArrayList<>();
ArrayList<Integer> l2 = new ArrayList<>(5);
l2.add(15);
l2.add(18);
l2.add(19);
l1.add(6);
l1.add(7);
l1.add(4);
l1.add(6);
l1.add(5);
l1.add(0,5);
l1.addAll(l2);
for(int i=0; i<l1.size(); i++){
System.out.println(l1.get(i)); //get() method is used to get ith element from
arraylist
}
}
}
Output:
5
6
7
4
6
5
15
18
19
]
[
Code:
package com.company;
//ArrayList - Advanced Java
// ArrayList can be resized, can we start inserting from a particular index,
// we can do things we wont be able to do with normal array
//All important Methods of ArrayList
import java.lang.reflect.Array;
import java.util.*;
public class cwh_91_arraylist {
public static void main(String[] args) {
ArrayList<Integer> l1 = new ArrayList<>();
ArrayList<Integer> l2 = new ArrayList<>(5);
l2.add(15);
l2.add(18);
l2.add(19);
l1.add(6);
l1.add(7);
l1.add(4);
l1.add(6);
l1.add(5);
l1.add(0,5);
l1.addAll(l2);
System.out.println(l1.contains(7));
System.out.println(l1.indexOf(7));
for(int i=0; i<l1.size(); i++){
System.out.print(l1.get(i)); //get() method is used to get ith element from
arraylist
System.out.print(", ");
}
}
}
Output:
true
2
5, 6, 7, 4, 6, 5, 15, 18, 19,
]
[
Code:
package com.company;
//ArrayList - Advanced Java
// ArrayList can be resized, can we start inserting from a particular index,
// we can do things we wont be able to do with normal array
//All important Methods of ArrayList
import java.lang.reflect.Array;
import java.util.*;
public class cwh_91_arraylist {
public static void main(String[] args) {
ArrayList<Integer> l1 = new ArrayList<>();
ArrayList<Integer> l2 = new ArrayList<>(5);
l2.add(15);
l2.add(18);
l2.add(19);
l1.add(6);
l1.add(7);
l1.add(4);
l1.add(6);
l1.add(5);
l1.add(0,5);
l1.addAll(l2);
System.out.println(l1.contains(7));
System.out.println(l1.indexOf(7));
System.out.println(l1.lastIndexOf(6));
//l1.clear(); --> for emptying
for(int i=0; i<l1.size(); i++){
System.out.print(l1.get(i)); //get() method is used to get ith element from
arraylist
System.out.print(", ");
}
}
}
Output:
true
2
4
5, 6, 7, 4, 6, 5, 15, 18, 19,
]
[
Code:
package com.company;
import java.util.ArrayDeque;
public class cwh_93_arraydeque {
public static void main(String[] args) {
ArrayDeque<Integer> ad1 = new ArrayDeque<>();
ad1.add(6);
ad1.add(56);
System.out.println(ad1.getFirst());
System.out.println(ad1.getLast());
}
}
Output:
6
56
]
[
Code:
package com.company;
//Hashset in Java
import java.util.HashSet;
//Default initial capacity is 16 and load factor is 0.75
public class cwh_95_set {
public static void main(String[] args) {
HashSet<Integer> myHashSet = new HashSet<>(6, 0.5F);
myHashSet.add(1);
myHashSet.add(11);
myHashSet.add(23);
myHashSet.add(12);
myHashSet.add(8);
System.out.println("HashSet is :");
System.out.println(myHashSet);
}
}
Output:
HashSet is :
[1, 23, 8, 11, 12]
]

More Related Content

DOCX
Main Java[All of the Base Concepts}.docx
PDF
Lecture 2 java.pdf
PPTX
Computer programming 2 chapter 1-lesson 2
PDF
3.Lesson Plan - Input.pdf.pdf
PDF
djkkfhulkgyftfdtrdrsdsjjjjjjjjjjjjjjjjjjj
PPT
Basic elements of java
PPTX
Reading and writting
PPTX
Lecture 3 and 4.pptx
Main Java[All of the Base Concepts}.docx
Lecture 2 java.pdf
Computer programming 2 chapter 1-lesson 2
3.Lesson Plan - Input.pdf.pdf
djkkfhulkgyftfdtrdrsdsjjjjjjjjjjjjjjjjjjj
Basic elements of java
Reading and writting
Lecture 3 and 4.pptx

Similar to All Of My Java Codes With A Sample Output.docx (20)

PDF
Howto get input with java
PPTX
Java works on different platforms (Windows, Mac, Linux, Raspberry Pi, etc.) I...
PDF
Sam wd programs
PPT
07-Basic-Input-Output.ppt
PDF
PSI 3 Integration
PPTX
Ch2 Elementry Programmin as per gtu oop.pptx
PPTX
Java Programming Tutorials Basic to Advanced 2
PPTX
Java fundamentals
PPTX
Lab 01jbjbjkbkbjkbkjbkjbkbkjbbnjjkb.pptx
PPTX
Lab 01hhkhkhkhkhkhkhkhkhjjjkhkkhhhhh.pptx
PPTX
Java chapter 2
DOCX
Java Program
PPTX
OBJECT ORIENTED PROGRAMMIING LANGUAGE PROGRAMS
PPTX
lab programs on java and dbms for students access
PPTX
02slide_accessible.pptx
PDF
Java Fundamentals
PPTX
JPC#8 Introduction to Java Programming
PDF
Java Lab Manual
PPTX
Class 2 variables, classes methods...
PDF
Java doc Pr ITM2
Howto get input with java
Java works on different platforms (Windows, Mac, Linux, Raspberry Pi, etc.) I...
Sam wd programs
07-Basic-Input-Output.ppt
PSI 3 Integration
Ch2 Elementry Programmin as per gtu oop.pptx
Java Programming Tutorials Basic to Advanced 2
Java fundamentals
Lab 01jbjbjkbkbjkbkjbkjbkbkjbbnjjkb.pptx
Lab 01hhkhkhkhkhkhkhkhkhjjjkhkkhhhhh.pptx
Java chapter 2
Java Program
OBJECT ORIENTED PROGRAMMIING LANGUAGE PROGRAMS
lab programs on java and dbms for students access
02slide_accessible.pptx
Java Fundamentals
JPC#8 Introduction to Java Programming
Java Lab Manual
Class 2 variables, classes methods...
Java doc Pr ITM2
Ad

Recently uploaded (20)

PDF
Sales and Distribution Managemnjnfijient.pdf
PPTX
_+✅+JANUARY+2025+MONTHLY+CA.pptx current affairs
PDF
MCQ Practice CBT OL Official Language 1.pptx.pdf
PPTX
FINAL PPT.pptx cfyufuyfuyuy8ioyoiuvy ituyc utdfm v
PDF
Daisia Frank: Strategy-Driven Real Estate with Heart.pdf
PPTX
Surgical thesis protocol formation ppt.pptx
PDF
Biography of Mohammad Anamul Haque Nayan
PPTX
PE3-WEEK-3sdsadsadasdadadwadwdsdddddd.pptx
PDF
Blue-Modern-Elegant-Presentation (1).pdf
PPTX
cse couse aefrfrqewrbqwrgbqgvq2w3vqbvq23rbgw3rnw345
PDF
シュアーイノベーション採用ピッチ資料|Company Introduction & Recruiting Deck
PDF
APNCET2025RESULT Result Result 2025 2025
PPTX
退学买新西兰毕业证(WelTec毕业证书)惠灵顿理工学院毕业证国外证书制作
PPTX
DPT-MAY24.pptx for review and ucploading
PPTX
PMP (Project Management Professional) course prepares individuals
PPTX
ESD MODULE-5hdbdhbdbdbdbbdbdbbdndbdbdbdbbdbd
PDF
L-0018048598visual cloud book for PCa-pdf.pdf
PPTX
Prokaryotes v Eukaryotes PowerPoint.pptx
PDF
Prostaglandin E2.pdf orthoodontics op kharbanda
DOC
field study for teachers graduating samplr
Sales and Distribution Managemnjnfijient.pdf
_+✅+JANUARY+2025+MONTHLY+CA.pptx current affairs
MCQ Practice CBT OL Official Language 1.pptx.pdf
FINAL PPT.pptx cfyufuyfuyuy8ioyoiuvy ituyc utdfm v
Daisia Frank: Strategy-Driven Real Estate with Heart.pdf
Surgical thesis protocol formation ppt.pptx
Biography of Mohammad Anamul Haque Nayan
PE3-WEEK-3sdsadsadasdadadwadwdsdddddd.pptx
Blue-Modern-Elegant-Presentation (1).pdf
cse couse aefrfrqewrbqwrgbqgvq2w3vqbvq23rbgw3rnw345
シュアーイノベーション採用ピッチ資料|Company Introduction & Recruiting Deck
APNCET2025RESULT Result Result 2025 2025
退学买新西兰毕业证(WelTec毕业证书)惠灵顿理工学院毕业证国外证书制作
DPT-MAY24.pptx for review and ucploading
PMP (Project Management Professional) course prepares individuals
ESD MODULE-5hdbdhbdbdbdbbdbdbbdndbdbdbdbbdbd
L-0018048598visual cloud book for PCa-pdf.pdf
Prokaryotes v Eukaryotes PowerPoint.pptx
Prostaglandin E2.pdf orthoodontics op kharbanda
field study for teachers graduating samplr
Ad

All Of My Java Codes With A Sample Output.docx

  • 1. Name – M ADHITYA ALL OF MY Java PROGRAMS [ Code: package com.company;//TIP To <b>Run</b> code, press <shortcut actionId="Run"/> or // click the <icon src="AllIcons.Actions.Execute"/> icon in the gutter. public class Main { public static void main(String[] args) { //TIP Press <shortcut actionId="ShowIntentionActions"/> with your caret at the highlighted text // to see how IntelliJ IDEA suggests fixing it. System.out.println("Hello World"); } } Output: Hello World ] [ Code: // storing integer in variable in java and printing package com.company;//TIP To <b>Run</b> code, press <shortcut actionId="Run"/> or // click the <icon src="AllIcons.Actions.Execute"/> icon in the gutter. public class Main { public static void main(String[] args) { //TIP Press <shortcut actionId="ShowIntentionActions"/> with your caret at the highlighted text // to see how IntelliJ IDEA suggests fixing it. int number = 8; //storing integer System.out.println(number); } }
  • 2. Output: 8 ] [ Code: package com.company;//TIP To <b>Run</b> code, press <shortcut actionId="Run"/> or // click the <icon src="AllIcons.Actions.Execute"/> icon in the gutter. public class Main { public static void main(String[] args) { //TIP Press <shortcut actionId="ShowIntentionActions"/> with your caret at the highlighted text // to see how IntelliJ IDEA suggests fixing it. System.out.print("The sum of the numbers is: "); int num1 = 2; int num2 = 3; int num3 = 4; int sum = num1 + num2 + num3; //sum of three numbers System.out.print(sum); } } Output: The sum of the numbers is: 9 Process finished with exit code 0 ] [ Code: package com.company; public class CH_04_Literals { public static void main(String[] args) { byte age = 34; System.out.print(age); char ch = 'A'; float f1 = 5.6f; double d1 = 5.66D; //By default decimal no. is double so can choose to not write D or d long ageDino = 5666666666666666l; //can write capital L short age3 = 87; //no need to write s for short literal boolean a = true; String str = " Adhi"; System.out.print(str); } }
  • 3. Output: 34 Adhi ] [ Code: package com.company; import java.util.Scanner; //Importing external Scanner class(import statement) public class CH_05_TakingInpu { public static void main(String[] args) { System.out.print("Taking Input From the User: "); Scanner sc = new Scanner(System.in); System.out.println("enter number 1: "); int a = sc.nextInt(); System.out.println("enter number 2: "); int b = sc.nextInt(); int sum = a+b; System.out.println("the sum of these numbers: "); System.out.print(sum); } } Output: Taking Input From the User: enter number 1: 2 enter number 2: 3 the sum of these numbers: 5 ]
  • 4. [ Code: package com.company; import java.util.Scanner; //Importing external Scanner class(import statement) public class CH_05_TakingInpu { public static void main(String[] args) { System.out.print("Taking Input From the User: "); Scanner sc = new Scanner(System.in); System.out.println("enter number 1: "); // int a = sc.nextInt(); float a = sc.nextFloat(); System.out.println("enter number 2: "); // int b = sc.nextInt(); float b = sc.nextFloat(); float sum = a+b; System.out.println("the sum of these numbers: "); System.out.print(sum); } } Output: Taking Input From the User: enter number 1: 2 enter number 2: 3 the sum of these numbers: 5.0 ]
  • 5. [ Code: package com.company; import java.util.Scanner; //Importing external Scanner class(import statement) public class CH_05_TakingInpu { public static void main(String[] args) { System.out.print("Taking Input From the User: "); Scanner sc = new Scanner(System.in); String str = sc.nextLine(); //nextLine method is used to read whole string line, and next method is used to only read first word System.out.print(str); } } Output: Taking Input From the User: 2 2 ] [ Code: package com.company; import java.util.Scanner; //Importing external Scanner class(import statement) public class CH_05_TakingInpu { public static void main(String[] args) { System.out.print("Taking Input From the User: "); Scanner sc = new Scanner(System.in); String str = sc.next(); System.out.print(str); } } Output: Taking Input From the User: Adhi Adhi ]
  • 6. [ Code: package com.company; // import java.util.Scanner; //Importing external Scanner class(import statement) public class CH_05_TakingInpu { public static void main(String[] args) { //calculating CGPA of 3 subjects float sub1 = 45; float sub2 = 97; float sub3 = 48; float cgpa = (sub1 + sub2 + sub3)/30; System.out.println(cgpa); } } Output: 6.3333335 ] [ Code: package com.company; import java.util.Scanner; //Importing external Scanner class(import statement) public class CH_05_TakingInpu { public static void main(String[] args) { //Taking Name as input and wishing them using string concatenation System.out.println("What is your name: "); Scanner sc = new Scanner(System.in); String name = sc.next(); System.out.println("Hello "+ name + " Have a good day!"); } } Output: What is your name: M Adhitya Hello M Have a good day! ]
  • 7. [ Code: package com.company; import java.util.Scanner; //Importing external Scanner class(import statement) public class CH_05_TakingInpu { public static void main(String[] args) { //Checking if input is Integer or not through Boolean System.out.println("Enter your number: "); Scanner sc = new Scanner(System.in); System.out.println(sc.hasNextInt()); } } Output: Enter your number: 23.8 false ] [ Code: package com.company; public class CWH_CH02_Operators { public static void main(String[] args) { int a = 4; //Operators int b = 6*a; System.out.println(b); } } Output: 24 ]
  • 8. [ Code: package com.company; public class CWH_CH02_Operators { public static void main(String[] args) { int a = 4; //Operators //int b = 6*a; int b = 9; b+=3; System.out.println(b); } } Output: 12 ] [ Code: package com.company; public class CWH_CH02_Operators { public static void main(String[] args) { int a = 4; //Operators //int b = 6*a; int b = 9; b+=3; System.out.println(b); System.out.println(6==8); // = is assignment operator and == is comparison operator System.out.println(64>9); } } Output: 12 false true ]
  • 9. [ Code: package com.company; public class CWH_CH02_Operators { public static void main(String[] args) { int a = 4; //Operators //int b = 6*a; int b = 9; b+=3; System.out.println(b); System.out.println(6==8); // = is assignment operator and == is comparison operator System.out.println(64>9); // && is logical operator System.out.println(64>5 && 64>8); } } Output: 12 false true true ] [ Code: package com.company; public class CWH_CH02_Operators { public static void main(String[] args) { int a = 5*6 - 34/5; //Precedence and Associativity in Java int b = 34/5 - 60*5; System.out.println(a); System.out.println(b); } } Output: 24 -294 ]
  • 10. [ Code: package com.company; public class CWH_CH02_Operators { public static void main(String[] args) { //Precedence and Associativity in Java int x = 6; int y = 1; int k = x*y/2; System.out.println(k); } } Output: 3 ] [ Code: package com.company; public class CWH_CH02_Operators { public static void main(String[] args) { //Precedence and Associativity in Java int x = 6; int y = 1; int k = x*y/2; System.out.println(k); int a = 1; int b = 2; int c = 3; int d = (b*b - 4*a*c)/(2*a); System.out.println(d); } } Output: 3 -4 ]
  • 11. [ Code: package com.company; public class CWH_10_resulting_data_type_ps1 { public static void main(String[] args) { int a = 654 + 6; //Resulting Data Type by Adding etc. 2 different data type byte x = 5; float b= 3.56f + x; int y = 6; short z = 8; System.out.println(b); } } Output: 8.559999 ] [ Code: package com.company; public class CWH_10_resulting_data_type_ps1 { public static void main(String[] args) { /* int a = 654 + 6; byte x = 5; float b= 3.56f + x; int y = 6; short z = 8; System.out.println(b);*/ // Increment and Decrement Operators int i = 56; System.out.println(i++); // i++ means print i then increment it System.out.println(i); System.out.println(++i); // ++i means print increment then print i System.out.println(i); } }
  • 12. Output: 56 57 58 58 ] [ Code: package com.company; public class CWH_10_resulting_data_type_ps1 { public static void main(String[] args) { int y = 7; System.out.println(++y*8); char ch = 'a'; System.out.println(++ch); //Increment } } Output: 64 B ]
  • 13. [ Code: package com.company; import java.util.Scanner; //Calculating CBSE board percentage public class CWH_10_resulting_data_type_ps1 { public static void main(String[] args) { Scanner scan = new Scanner(System.in); System.out.println("Enter your Physics marks: "); int physics = scan.nextInt() ;//nextInt() is used for input System.out.println("Enter your English marks: "); int english = scan.nextInt(); System.out.println("Enter your Chemistry marks: "); int chemistry = scan.nextInt(); System.out.println("Enter your Mathematics marks: "); int mathematics = scan.nextInt(); System.out.println("Enter your computer science marks:"); int computer = scan.nextInt(); float r = ((physics + english+chemistry+mathematics+computer)/500.0f)*100; System.out.println("Your Percentage is:"); System.out.println(r); } } Output: Enter your Physics marks: 95 Enter your English marks: 97 Enter your Chemistry marks: 84 Enter your Mathematics marks: 86 Enter your computer science marks: 92 Your Percentage is: 90.8 ]
  • 14. [ Code: package com.company; public class CWH_10_resulting_data_type_ps1 { public static void main(String[] args) { float a = 7/4.0f *9/2.0f ; // arithmetic between int and i t is int, to get correct value convert to float System.out.println(a); } } Output: 7.875 ] [ Code: package com.company; public class CWH_CH12_ps2_pr01 { public static void main(String[] args) { //Type casting used as (char) to convert (grade+8) which is int to char char grade = 'B'; grade = (char)(grade+8); //In type casting no need to write type in start as usual System.out.println(grade); grade = (char)(grade-8); System.out.println(grade); } } Output: J B ]
  • 15. [ Code: package com.company; import java.util.Scanner; public class CWH_CH12_ps2_pr01 { public static void main(String[] args) { //To check if Given number is greater than user defined or not using user defined functioned Scanner sc = new Scanner(System.in); int a = sc.nextInt(); System.out.println(a>8); } } Output: 4 False ] [ Code: package com.company; import java.util.Scanner; public class CWH_CH12_ps2_pr01 { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int v = sc.nextInt(); int u = sc.nextInt(); int a = sc.nextInt(); int s = sc.nextInt(); float r = (float)(v*v - u*u)/(2*a*s); System.out.println(r); } } Output: 2 3 4 5
  • 16. -0.125 ] [ Code: package com.company; public class CWH_16_conditionals{ public static void main(String[] args) { int age = 20; if (age>18){ System.out.println("yes boy you can drive"); } // else{ // System.out.println("No boy you cannot drive yet"); // } } } Output: yes boy you can drive ] [ Code: package com.company; public class CWH_16_conditionals{ public static void main(String[] args) { int age = 20; if (age!=18){ //Using relational operators System.out.println("yes boy you can drive"); } else{ System.out.println("No boy you cannot drive yet"); } } } Output: yes boy you can drive ]
  • 17. [ Code: package com.company; public class Main { public static void main(String[] args) { boolean a = true; boolean b = false; if (a&&b){ System.out.println("Y"); } else{ System.out.println("N"); } } } Output: N ] [ Code: package com.company; public class Main { public static void main(String[] args) { boolean a = true; boolean b = false; boolean c = true; if (a&&b&&c){ System.out.println("Y"); } else{ System.out.println("N"); } } } Output: N ]
  • 18. [ Code: package com.company; import java.util.Scanner; public class CWH_16_conditionals{ public static void main(String[] args) { int age; Scanner sc = new Scanner(System.in); age = sc.nextInt(); if (age>56){ System.out.println("You are experienced"); } else if (age>46){ System.out.println("You are semi-experienced"); } else if (age>36){ System.out.println("You are semi-semi-experienced"); } else{ System.out.println("You are not experienced"); } } } Output: 38 You are semi-semi-experienced ] [ Code: package com.company; import java.util.Scanner; public class CWH_16_conditionals{ public static void main(String[] args) { int age; System.out.println("Enter age"); Scanner sc = new Scanner(System.in); age = sc.nextInt(); switch(age){ case 18: System.out.println("You are an Adult"); break; case 20:
  • 19. System.out.println("You are going to get a job"); break; case 60: System.out.println("You are going to get retired"); break; default: System.out.println("Enjoy your Life!"); } } } Output: Enter age 38 Enjoy your Life! ] [ Code: package com.company; import java.util.Scanner; public class CWH_16_conditionals{ public static void main(String[] args) { String var = "Harry"; Scanner sc = new Scanner(System.in); switch(var){ case "Saurabh": System.out.println("You are an Adult"); break; case "Harry" : System.out.println("You are going to get a job"); break; case "Adhitya" : System.out.println("You are going to get retired"); break; default: System.out.println("Enjoy your Life!"); } } }
  • 20. Output: You are going to get a job ] [ Code: package com.company; import java.util.Scanner; public class CWH_16_conditionals{ public static void main(String[] args) { String var = "Harry"; Scanner sc = new Scanner(System.in); switch (var) { case "Saurabh" -> System.out.println("You are an Adult"); //Enhanced switch statement case "Harry" -> System.out.println("You are going to get a job"); case "Adhitya" -> System.out.println("You are going to get retired"); default -> System.out.println("Enjoy your Life!"); } } } Output: You are going to get a job ] [ Code: package com.company; import java.util.Scanner; public class CWH_16_conditionals{ public static void main(String[] args) { int a = 10; if (a==11){ System.out.println("I am 11"); } else{ System.out.println("I am not 11"); } } }
  • 21. Output: I am not 11 ] [ Code: package com.company; import java.util.Scanner; public class CWH_16_conditionals{ public static void main(String[] args) { //Find if a student is pass or fail // use byte as number is below or equal to 100 byte m1,m2,m3; Scanner sc = new Scanner(System.in); System.out.println("Enter your marks in Physics"); m1 = sc.nextByte(); System.out.println("Enter your marks in Chemistry"); m2 = sc.nextByte(); System.out.println("Enter your marks in Mathematics"); m3 = sc.nextByte(); float avg = (m1+m2+m3)/3.0f; if (avg>=40 && m1>=33 && m2>=33 && m3>=33){ System.out.println("Congrats, you are promoted"); } else{ System.out.println("repeat the course"); }
  • 22. } } Output: Enter your marks in Physics 95 Enter your marks in Chemistry 84 Enter your marks in Mathematics 86 Congrats, you are promoted ] [ Code: package com.company; import java.util.Scanner; public class CWH_16_conditionals{ public static void main(String[] args) { //Problem- write java problem to find out the day of the week given number(1- Monay, 2-Tuesday, etc.) Scanner sc = new Scanner(System.in); System.out.println("enter number of day: "); int day = sc.nextInt(); switch(day){ case 1-> System.out.println("Monday"); case 2-> System.out.println("Tuesday"); case 3-> System.out.println("Wednesday"); case 4-> System.out.println("Thursday"); case 5-> System.out.println("Friday"); case 6-> System.out.println("Saturday"); case 7-> System.out.println("Sunday"); } } }
  • 23. Output: enter number of day: 2 Tuesday ] [ Code: package com.company; import java.util.Scanner; public class CWH_16_conditionals{ public static void main(String[] args) { //Problem - From URL from user find out what type of website it is Scanner sc = new Scanner(System.in); System.out.println("Enter URL"); String website = sc.nextLine(); if (website.endsWith(".org")){ System.out.println("Organizational website"); } else if (website.endsWith(".com")){ System.out.println("Commercial website"); } else if (website.endsWith(".in")){ System.out.println("Indian website"); } } }
  • 24. Output: Enter URL https://www.youtube.com Commercial website ] [ Code: package com.company; import java.util.Scanner; public class CWH_16_conditionals{ public static void main(String[] args) { int i = 1; System.out.println("Using Loops: "); while(i<=3){ System.out.println(i); i++; } System.out.println("Finished using Loops! "); } } Output: Using Loops: 1 2 3 Finished using Loops! ]
  • 25. [ Code: package com.company; public class CWH_22_do_while { public static void main(String[] args) { int a =0; while(a<5){ System.out.println(a); a++; } } } Output: 0 1 2 3 4 ] [ Code: package com.company; public class CWH_22_do_while { public static void main(String[] args) { int b=10; do{ System.out.println(b); //do-while loop executes first loop without checking condition b++; }while(b<5); } } Output: 10 ]
  • 26. [ Code: package com.company; public class CWH_22_do_while { public static void main(String[] args) { int c =1; do{ System.out.println(c); c++; }while(c<=45); } } Output: 1 2 3 4 5 6 7 8 9 10
  • 28. 40 41 42 43 44 45 ] [ Code: package com.company; public class CWH_23_for_loop { public static void main(String[] args) { for (int i =1;i<=10; i++){ System.out.println(i); } } } Output: 1 2 3 4 5 6 7 8 9 10 ]
  • 29. [ Code: package com.company; public class CWH_23_for_loop { public static void main(String[] args) { int n = 5; for (int i = 0; i<=5; i++){ System.out.println(2*i+1); } } } Output: 1 3 5 7 9 11 ] [ Code: package com.company; public class CWH_23_for_loop { public static void main(String[] args) { for(int i =5; i!=0; i--){ System.out.println(i); } } }
  • 30. Output: 5 4 3 2 1 ] [ Code: package com.company; public class CWH_23_for_loop { public static void main(String[] args) { //break and continue using loops for (int i =0; i<5; i++){ System.out.println(i); System.out.println("Java is great"); if (i==2){ System.out.println("Ending the loop"); break; } } } } Output: 0 Java is great 1 Java is great 2 Java is great Ending the loop ]
  • 31. [ Code: package com.company; public class CWH_24_break_and_continue { public static void main(String[] args) { //Practice Problem 1 - Create pattern of * using loop int n =4; for (int i=n; i>0; i--){ for (int j=0; j<i;j++){ System.out.print("*"); } System.out.println("n"); } } } Output: **** *** ** * ] [ Code: package com.company; public class CWH_24_break_and_continue { public static void main(String[] args) { //Practice Problem 2 - sum of first n even numbers int sum=0; int n=4; for (int i=0;i<n;i++){ sum = sum + (2*i); } System.out.print("Sum of first %d even numbers "); System.out.println(sum); } }
  • 32. Output: Sum of first %d even numbers 12 Process finished with exit code 0 ] [ Code: package com.company; public class CWH_24_break_and_continue { public static void main(String[] args) { //Problem - Write a program to print multiplication of a number n int n=5; for (int i=1; i<=10;i++){ System.out.printf("%d X %d = %d", n,i, n*i); System.out.println("n"); } } } Output: 5 X 1 = 5 5 X 2 = 10 5 X 3 = 15 5 X 4 = 20 5 X 5 = 25
  • 33. 5 X 6 = 30 5 X 7 = 35 5 X 8 = 40 5 X 9 = 45 5 X 10 = 50 ] [ Code: package com.company; import java.util.Scanner; import java.util.Scanner; public class CWH_24_break_and_continue { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.print("Enter a number: "); int number = scanner.nextInt(); scanner.close(); long factorial = 1; for (int i = 1; i <= number; i++) { factorial *= i; } System.out.println("Factorial of " + number + " is: " + factorial); } } Output: Enter a number: 6 Factorial of 6 is: 720 ]
  • 34. [ Code: package com.company; import java.util.Scanner; public class CWH_24_break_and_continue { public static void main(String[] args) { //Problem- Factorial using while loop int n=5; // what is factorial = n*n-1*n-2..1 int i =1; //5!=5*4*3*2*1 int factorial =1; while(i<=n){ factorial*=i; i++; } System.out.println(factorial); } } Output: 120 ] [ Code: package com.company; import java.util.Scanner; public class CWH_24_break_and_continue { public static void main(String[] args) { //print sum of the numbers in product side of multiplication table of 8 int n=8; int sum=0; for (int i=1; i<=10; i++){ sum+=n*i; } System.out.println(sum); } } Output: 440 ]
  • 35. [ Code: package com.company; public class cwh_26_arrays { public static void main(String[] args) { //Classroom of 5 marks - you have to store marks of 500 students //You have 2 options- //1. create 5 variables //2.Use arrays //Array is a collection of similar types of data // array format is [datatype[] arrayName] int [] marks = new int[5]; marks[0]= 50; marks[1]=70; marks[2]=30; marks[3]=86; marks[4]=93; System.out.println(marks[4]); } } Output: 93 ] [ Code: package com.company; public class cwh_26_arrays { public static void main(String[] args) { //Other ways of declaring arrays //method -2 int []marks; marks = new int[5]; //method -3 int [] list ={100,70,80,45,71}; System.out.println(list[2]); } } Output: 80 ]
  • 36. [ Code: package com.company; public class cwh_27_arrays { public static void main(String[] args) { int [] marks = {100,30,80,96,78}; System.out.println(marks[3]); System.out.println(marks.length); float [] marks1 = {45.1f, 76.3f, 67.3f, 98.5f, 46}; System.out.println(marks1[4]); String [] students = {"Harry", "Lovish", "Rohan", "Shubham"}; System.out.println(students.length); } } Output: 96 5 46.0 4 ]
  • 37. [ Code: package com.company; public class cwh_27_arrays { public static void main(String[] args) { int [] marks = {100,30,80,96,78}; System.out.println(marks[3]); System.out.println(marks.length); float [] marks1 = {45.1f, 76.3f, 67.3f, 98.5f, 46}; System.out.println(marks1[4]); String [] students = {"Harry", "Lovish", "Rohan", "Shubham"}; System.out.println(students.length); //Displaying array // Forward using for loop for (int i=0; i<marks.length; i++){ System.out.println(i); } // reverse using for loop for (int i = marks.length -1; i>=0; i--){ System.out.println(i); } //for each loop for displaying System.out.println("Printing using for-each loop"); for (int element: marks){ System.out.println(element); } } } Output: 96 5 46.0 4 0 1 2 3 4 4
  • 38. 3 2 1 0 Printing using for-each loop 100 30 80 96 78 ] [ Code: package com.company; public class cwh_29_Practice_Set_6 { public static void main(String[] args) { //Problem - create an array of 5 floats and find their sum float [] marks = {45.7f, 34.6f, 100.0f, 93.5f, 94.8f}; float sum =0; for (float element : marks){ sum = sum+ element; } System.out.println("the value of sum is: "); System.out.println(sum); } } Output: the value of sum is: 368.59998 ]
  • 39. [ Code: package com.company; public class cwh_29_Practice_Set_6 { public static void main(String[] args) { //Problem - create an array of 5 floats and find their sum float [] marks = {45.7f, 34.6f, 100.0f, 93.5f, 94.8f}; float num = 45.7f; boolean isInArray= false; for (float element : marks){ if (num==element){ isInArray=true; break; } } if (isInArray){ System.out.println("the value is present in the Array"); } else{ System.out.println("the value is not present in the Array"); } } } Output: the value is present in the Array ]
  • 40. [ Code: package com.company; public class cwh_29_Practice_Set_6 { public static void main(String[] args) { //Problem - calculate average of marks of an array containing marks of all students in physics int [] marks = {34, 56, 78, 98, 100}; int sum = 0; for (int i =0; i< marks.length; i++){ sum = sum + i; } int avg = sum/marks.length; System.out.print("Average of the numbers in the array is "); System.out.println(avg); //Using for each loop for (int element : marks){ sum = sum + element; } System.out.println("Average using for each loop is "+ sum/marks.length); } } Output: Average of the numbers in the array is 2 Average using for each loop is 75 ]
  • 41. [ Code: package com.company; public class cwh_29_Practice_Set_6 { public static void main(String[] args) { //Problem - create a java program to add 2 matrices of size 2X3 // we will do it using arrays int [][]mat1 = {{1,2,3}, {4,5,6}}; // as in 2-D arrays it is equivalent to [row][column] int [][] mat2 = {{2,5,6}, {12, 43, 1}}; int [][] result ={{0,0,0}, {0,0,0}}; for (int i=0; i< mat1.length; i++){ for (int j=0; j< mat1[i].length; j++){ result[i][j] = mat1[i][j]+ mat2[i][j]; System.out.printf(result[i][j]+ " "); } System.out.print("n"); } } } Output: 3 7 9 16 48 7 ] [ Code: package com.company; public class cwh_31_methods { public static void main(String[] args) { int a= 5; int b=7; int c= (a+b)*5; System.out.println(c); } } Output: 60 ]
  • 42. [ Code: package com.company; public class cwh_31_methods { public static void main(String[] args) { int a= 5; int b=7; int c; if (a>b){ c = a+b; } else{ c = (a+b)*5; } int a1=2; int b1=1; int c1; if (a1>b1){ c1 =a1+b1; } else{ c1 = (a1+b1)*5; } System.out.println(c); System.out.println(c1); } } Output: 60 3 ]
  • 43. [ Code: package com.company; public class cwh_31_methods { //Java methods is equivalent to functions in Python static int logic(int x, int y){ int z; if (x>y){ z = x+y; } else{ z = (x+y)*5; } return z; } public static void main(String[] args) { int a= 5; 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); } } Output: 60 3 ]
  • 44. [ Code: package com.company; public class cwh_31_methods { //Java method belongs to the class. Without static keyword, we have to make object and call as shown // only static methods can be called directly within public static void main(String[] args) // Method invocation using object creation int logic(int x, int y){ int z; if (x>y){ z = x+y; } else{ z = (x+y)*5; } return z; } public static void main(String[] args) { int a= 5; int b=7; int c; cwh_31_methods obj = new cwh_31_methods(); c =obj.logic(a,b); int a1=2; int b1=1; int c1; c1 = obj.logic(a1, b1); System.out.println(c); System.out.println(c1); } } Output: 60 3 ] [ Code: package com.company; public class cwh_32_method_overloading { static void tellJoke(){ System.out.println("I invented a new word n" + "Plagiarism!"); } public static void main(String[] args) { tellJoke(); } }
  • 45. Output: I invented a new word Plagiarism! ] [ Code: package com.company; public class cwh_32_method_overloading { static void change(int a){ a = 98; } public static void main(String[] args) { int x = 45; change(x); //copy of x's value goes to method change and hence actual value of x doesnt change System.out.println( "the value of x after change method is "+ x); } } Output: the value of x after change method is 45 ] [ Code: package com.company; public class cwh_32_method_overloading { static void change(int a){ a = 98; } static void change2(int [] arr){ arr[0]= 98; } public static void main(String[] args) { // Case 1 - Changing the integer //int x = 45; // change(x); //copy of x's value goes to method change and hence actual value of x doesnt change // System.out.println( "the value of x after change method is "+ x); // value of x didn't change. It will change only if reference is passed and not the copy of the object //Case 2- Changing the Array int [] marks = {52, 76, 98, 56, 78, 93}; change2(marks); // marks is reference. As reference is passed into change2, // arr and marks refer to the same array and marks[0] value changes System.out.println("the first value of array after change2 "+ marks[0]); } }
  • 46. Output: the first value of array after change2 98 ] [ Code: package com.company; public class cwh_32_method_overloading { //Method Overloading - same name methods with different parameters static void foo(){ System.out.println("Good morning Bro! "); } static void foo(int a){ System.out.println("Good morning "+ a + " Bro!"); } public static void main(String[] args) { foo(); foo(34); } // a is parameter while 34 is argument }//Arguments are actual! //Cannot do overloading by changing return type. Void is return type, int is return type. //Both void and int return types are written beside static Output: Good morning Bro! Good morning 34 Bro! ]
  • 47. [ Code: package com.company; public class cwh_33_varargs { static int sum(int a, int b){ return a+b; } static int sum(int a, int b,int c){ return a+b+c; } // Varargs method to replace all the above methods static int sum(int ...arr){ // Available as int [] arr int result = 0; for (int a : arr){ result+=a; } return result; } public static void main(String[] args) { System.out.println("Welcome to Varargs Tutorial"); System.out.println("Sum of 4 and 5 is "+ sum(4,5)); System.out.println("Sum of 4 and 5 is "+ sum(4,3,5)); // further if we want to get sum for n numbers we cannot keep doing overloading // to solve this we use varargs System.out.println("Sum of Random number of numbers by varargs is "+ sum(4,5,6,7,8,9,2,122,2332)); } } Output: Welcome to Varargs Tutorial Sum of 4 and 5 is 9 Sum of 4 and 5 is 12 Sum of Random number of numbers by varargs is 2495 ]
  • 48. [ Code: package com.company; public class cwh_33_varargs { static int sum(int a, int b){ return a+b; } static int sum(int a, int b,int c){ return a+b+c; } // Varargs method to replace all the above methods static int sum(int x, int ...arr){ // Available as int [] arr int result = x; for (int a : arr){ result+=a; } return result; } public static void main(String[] args) { System.out.println("Welcome to Varargs Tutorial"); System.out.println("Sum of 4 and 5 is "+ sum(4,5)); System.out.println("Sum of 4 and 5 is "+ sum(4,3,5)); // further if we want to get sum for n numbers we cannot keep doing overloading // to solve this we use varargs System.out.println("Sum of Random number of numbers by varargs is "+ sum(4,5,6,7,8,9,2,122,2332)); } } Output: Welcome to Varargs Tutorial Sum of 4 and 5 is 9 Sum of 4 and 5 is 12 Sum of Random number of numbers by varargs is 2495 ]
  • 49. [ Code: package com.company; //Recursion is when the function/method calls itself when it is executed //factorial can be done using recursion public class cwh_34_recursion { static int factorial(int n){ if (n==0 || n==1){ return 1; } else{ return n* factorial(n-1); } } public static void main(String[] args) { int n=4; System.out.println("Factorial of 4 is "+ factorial(n)); } } Output: Factorial of 4 is 24 ] [ Code: package com.company; //Problem- multiplication of a number using Java methods public class cwh_34_recursion { static void multiplication(int n){ for (int i =0; i<=10; i++){ System.out.printf("%d X %d = %dn", n, i, n*i); } } public static void main(String[] args) { multiplication(7); } } Output: 7 X 0 = 0 7 X 1 = 7 7 X 2 = 14 7 X 3 = 21
  • 50. 7 X 4 = 28 7 X 5 = 35 7 X 6 = 42 7 X 7 = 49 7 X 8 = 56 7 X 9 = 63 7 X 10 = 70 ] [ Code: package com.company; //Problem- Create desired pattern using Java methods public class cwh_34_recursion { static void star(int n){ for (int i=1; i<=n; i++){ for (int j=0; j<i; j++){ System.out.print("*"); } System.out.println(); } } public static void main(String[] args) { star(4); } } Output: * ** *** **** ]
  • 51. [ Code: package com.company; //Problem-write a recursive function to find sum of first n natural numbers public class cwh_34_recursion { static int sumRec(int n){ if (n==1){ return 1; } else{ return n+ sumRec(n-1); } } public static void main(String[] args) { int c = sumRec(4); System.out.print("Sum of n natural numbers using recursion function is "); System.out.println(c); } } Output: Sum of n natural numbers using recursion function is 10 ] [ Code: package com.company; //Problem- Create desired pattern using Java methods public class cwh_34_recursion { static void star(int n){ for (int i=1; i<=n; i++){ for (int j=n; j>i -1; j--){ System.out.print("*"); } System.out.println(); } } public static void main(String[] args) { star(4); } }
  • 52. Output: **** *** ** * ] [ Code: package com.company; //Problem- write a function to print nth term of the fibonnaci series using recursion // fibonacci series - 0,1,1,2,3,5,8,13,21,34,... public class cwh_34_recursion { static int fib(int n){ if (n==1){ return 0; } else if (n==2){ return 1; } else{ return fib(n-1)+fib(n-2); } } public static void main(String[] args) { int c = fib(8); System.out.print("nth term of the Fibonacci series is "); System.out.println(c); } } Output: nth term of the Fibonacci series is 13 ]
  • 53. [ Code: package com.company; //custom class has attributes within it //there can be only one 1 public class in 1 java file class Employee{ int id; int salary; String name; //String data type has S capital //Just as methpd/function has parameters, Java class has attrubutes to create objects with new keyword public void printDetails(){ System.out.println("My id is "+ id); System.out.println("My name is "+ name); } public int getSalary(){ return salary; } } public class cwh_38_custom_class { public static void main(String[] args) { System.out.println("This is our First Custom Class"); //Setting attributes Employee harry = new Employee(); harry.id = 12; harry.name = "CodeWithHarry"; harry.salary = 12; Employee Adhitya = new Employee(); Adhitya.id = 1; Adhitya.name = "M Adhitya"; Adhitya.salary = 100; //Any real world object = properties + Behavior; similarly //objects in OOPs = attributes + methods //Printing the properties/attributes- System.out.println("Adhitya's id- "); System.out.print(Adhitya.id); System.out.println("Adhitya's full name- "); System.out.println(Adhitya.name); //Instead of again and again writing like above, we would like to call a method System.out.println("Adhitya's details using custom method in custom class- "); Adhitya.printDetails();// as sout in printDetails already, dont write Adhitya.printDetails() withing sout here System.out.println(harry.getSalary()); System.out.println(Adhitya.getSalary()); } }
  • 54. Output: This is our First Custom Class Adhitya's id- 1Adhitya's full name- M Adhitya Adhitya's details using custom method in custom class- My id is 1 My name is M Adhitya 12 100 ] [ Code: package com.company; //Problem - Create Employee1 custom class class Employee1 { int salary; String name; public int getSalary() { return salary; } public String getName() { return name; } public void setName(String n) { name = n; } } public class cwh_39_ch8_ps { public static void main(String[] args) { Employee1 Harry = new Employee1(); Harry.setName("Adhitya"); Harry.salary = 123; System.out.println(Harry.getName()); System.out.println(Harry.getSalary()); } }
  • 55. Output: Adhitya 123 ] [ Code: package com.company; //Problem - Create class CellPhone which prints ringing.. vibrating.. etc. class CellPhone{ public void ring(){ System.out.println("Ringing..."); } public void vibrate(){ System.out.println("Vibrating..."); } public void callFriend (){ System.out.println("calling Aaditya Aryan"); } } public class cwh_39_ch8_ps { public static void main(String[] args) { CellPhone samsung = new CellPhone(); samsung.callFriend(); samsung.ring(); samsung.vibrate(); } } Output: calling Aaditya Aryan Ringing... Vibrating... ]
  • 56. [ Code: package com.company; //Problem- create class square with a initialize its side, calculating area, perimeter, etc class Square{ int side; public float area(){ return side*side; } public int perimeter(){ return 4*side; } } public class cwh_39_ch8_ps { public static void main(String[] args) { Square a = new Square(); a.side = 4; System.out.println(a.area()); System.out.println(a.perimeter()); } } Output: 16.0 16 ] [ Code: package com.company; //Problem- create class Tommy capable of hitting, firing, running, etc. class Tommy{ public void hit(){ System.out.println("Hitting the enemy"); } public void run(){ System.out.println("Running from Enemy"); } public void fire(){ System.out.println("Firing the enemy"); } } public class cwh_39_ch8_ps { public static void main(String[] args) { Tommy player1 = new Tommy(); player1.hit(); player1.run(); player1.fire(); } }
  • 57. Output: Hitting the enemy Running from Enemy Firing the enemy ] [ Code: package com.company; class MyEmployee{ private int id; private String name; public void setName(String n){ this.name = n; } public String getName(){ return name; } public void setId(int i){ this.id = i; //this and other keywords here are access modifiers, getters & setters. } public int getId(){ return id; } } public class cwh_40_ch9 { public static void main(String[] args) { MyEmployee Adhitya = new MyEmployee(); // Adhitya.id = 45; // Adhitya.name = "Adhi; --> throws an error due to private access modifier Adhitya.setName("Adhitya"); System.out.println("Adhitya's id after changing is - "+ Adhitya.getId()); System.out.println(Adhitya.getName()); } } Output: Adhitya's id after changing is - 0 Adhitya ]
  • 58. [ Code: package com.company; import java.util.Scanner; import java.util.Random; //Rock Paper Scissor Game public class cwh_ex2_soln { public static void main(String[] args) { // 0 for Rock //1 for Paper // 2 for Scissor Scanner sc = new Scanner(System.in); int userInput = sc.nextInt(); Random random = new Random(); int computerInput = random.nextInt(); if (userInput==computerInput){ System.out.println("Draw"); } else if ((userInput==0 && computerInput ==2) || (userInput==1 &&computerInput==0) || (userInput ==2 && computerInput==1)){ System.out.println("You Win!"); } else{ System.out.println("Computer Wins"); } } } Output: 1 Computer Wins ]
  • 59. [ Code: package com.company; //Problem - create a class cylinder and use getters and setters to set its radius and height class Cylinder{ private int radius; private int height; //Click the three dots above and choose "code" then click "Generate" then use it to //generate code like getter and setters - short trick public int getHeight() { return height; } public void setHeight(int height) { this.height = height; } public int getRadius() { return radius; } public void setRadius(int radius) { this.radius = radius; } } public class cwh_44_ps09 { public static void main(String[] args) { Cylinder myCylinder = new Cylinder(); myCylinder.setHeight(13); int h = myCylinder.getHeight(); System.out.println(h); myCylinder.setRadius(3); System.out.println(myCylinder.getRadius()); } } Output: 13 3 ]
  • 60. [ Code: package com.company; //Problem - create a class cylinder and use getters and setters to set its radius and height //with surface area and volume class Cylinder{ private int radius; private int height; //Click the three dots above and choose "code" then click "Generate" then use it to //generate code like getter and setters - short trick public int getHeight() { return height; } public void setHeight(int height) { this.height = height; } public int getRadius() { return radius; } public void setRadius(int radius) { this.radius = radius; } public double surfaceArea(){ return 2*3.14*radius*radius + 2*3.14*radius*height; } public double volume(){ return 3.14*radius*radius*height; } } public class cwh_44_ps09 { public static void main(String[] args) { Cylinder myCylinder = new Cylinder(); myCylinder.setHeight(13); int h = myCylinder.getHeight(); System.out.println(h); myCylinder.setRadius(3); System.out.println(myCylinder.getRadius()); System.out.println(myCylinder.volume()); System.out.println(myCylinder.surfaceArea()); } } Output: 13 3 367.38 301.44 ]
  • 61. [ Code: package com.company; //Problem - create a class cylinder and use constructors to set its radius and height //with surface area and volume class Cylinder{ private int radius; private int height; public Cylinder(int radius, int height) { this.radius = radius; this.height = height; //Using Constructor } //Click the three dots above and choose "code" then click "Generate" then use it to //generate code like getter and setters - short trick public int getHeight() { return height; } public void setHeight(int height) { this.height = height; } public int getRadius() { return radius; } public void setRadius(int radius) { this.radius = radius; } public double surfaceArea(){ return 2*Math.PI*radius*radius + 2*3.14*radius*height; } public double volume(){ return Math.PI*radius*radius*height; //use Math.PI for accurate value of Pi } } public class cwh_44_ps09 { public static void main(String[] args) { Cylinder myCylinder = new Cylinder(12,9); // myCylinder.setHeight(13); int h = myCylinder.getHeight(); System.out.println(h); // myCylinder.setRadius(3); System.out.println(myCylinder.getRadius()); System.out.println(myCylinder.volume()); System.out.println(myCylinder.surfaceArea()); } }
  • 62. Output: 9 12 4071.5040790523717 1583.0186842338603 ] [ Code: package com.company; //Problem - overload a constructor used to initialize a rectangle of length 4 and breadth 5 // for using custom parameters class Rectangle { private int length; private int breadth; public Rectangle(int length, int breadth) { this.length = length; this.breadth = breadth; } public int getLength() { return length; } public void setLength(int length) { this.length = length; } public int getBreadth() { return breadth; } public void setBreadth(int breadth) { this.breadth = breadth; } } //Click the three dots above and choose "code" then click "Generate" then use it to //generate code like getter and setters - short trick public class cwh_44_ps09 { public static void main(String[] args) { Rectangle r = new Rectangle(4,5); System.out.println(r.getBreadth()); System.out.println(r.getLength()); } }
  • 63. Output: 5 4 ] [ Code: package com.company; //Problem - create a class Sphere and use getters and setters to print its surface area and volume //Click the three dots above and choose "code" then click "Generate" then use it to //generate code like getter and setters - short trick class Sphere{ private int radius; public void setRadius(int r){ radius = r; } public int getRadius(){ return radius; } public float area(){ return (float) (4*Math.PI*radius*radius); } public double volume(){ return (4/3)*Math.PI*radius*radius*radius; } } public class cwh_44_ps09 { public static void main(String[] args) { Sphere s = new Sphere(); s.setRadius(5); System.out.println(s.getRadius()); System.out.println(s.area()); System.out.println(s.volume()); } } Output: 5 314.15927 392.69908169872417 ]
  • 64. [ Code: package com.company; //Inheritance concept class Base{ int x; public int getX() { return x; } public void setX(int x) { System.out.println("I am in base and I am setting value of X now"); this.x = x; } public void printMe(){ System.out.println("I am a constructor"); } } //Inheritance uses existing class to create new class in such a way, // such that the code of previous class is also there behind the screen in current class class Derived extends Base{ int y; public int getY() { return y; } public void setY(int y) { this.y = y; } } public class cwh_45_inheritance { public static void main(String[] args) { //Creating an object of base class Base b = new Base(); b.setX(23); System.out.println(b.getX()); //Creating an object of derived class in inheritance Derived d = new Derived(); d.setX(23); System.out.println(d.getX()); } } Output: I am in base and I am setting value of X now 23 I am in base and I am setting value of X now 23 ]
  • 65. [ Code: package com.company; class Base1 { Base1() { //Constructor is exact copypaste of method, just that its name is same as that of class System.out.println("I am a Constructor"); } Base1(float x) { System.out.println("I am an Overloaded Constructor with a value of " + x); } } class Derived1 extends Base1 { Derived1() { super(0); //To use an argumented Constructed in derived class we use super keyword System.out.println("I am derived class constructor"); } } public class cwh_46_constructors_in_inheritance { public static void main(String[] args) { Derived1 d = new Derived1(); } } Output: I am an Overloaded Constructor with a value of 0.0 I am derived class constructor ]
  • 66. [ Code: package com.company; class Base1 { Base1() { //Constructor is exact copypaste of method, just that its name is same as that of class System.out.println("I am a Constructor"); } Base1(float x) { System.out.println("I am an Overloaded Constructor with a value of " + x); } } class Derived1 extends Base1 { Derived1() { super(0); //To use an argumented Constructed in derived class we use super keyword System.out.println("I am derived class constructor"); } Derived1(int x, int y){ super(x); System.out.println("I am an Overloaded Constructor with a value of " + y); } } public class cwh_46_constructors_in_inheritance { public static void main(String[] args) { //Derived1 d = new Derived1(); Derived1 d = new Derived1(4,9); } } Output: I am an Overloaded Constructor with a value of 4.0 I am an Overloaded Constructor with a value of 9 ]
  • 67. [ Code: package com.company; class Base1 { Base1() { //Constructor is exact copypaste of method, just that its name is same as that of class System.out.println("I am a Constructor"); } Base1(int x) { System.out.println("I am an Overloaded Constructor with a value of " + x); } } class Derived1 extends Base1 { Derived1() { super(0); //To use an argumented Constructed in derived class we use super keyword System.out.println("I am derived class constructor"); } Derived1(int x, int y){ super(x); System.out.println("I am an Overloaded Constructor with a value of " + y); } } class ChildOfDerived1 extends Derived1{ ChildOfDerived1(){ System.out.println("I am a child of derived"); } ChildOfDerived1(int x, int y, int z){ super(x, y); System.out.println("I am an overloaded constructor of child of derived with value of z as "+ z); } } public class cwh_46_constructors_in_inheritance { public static void main(String[] args) { //Derived1 d = new Derived1(); // Derived1 d = new Derived1(4,9); ChildOfDerived1 t = new ChildOfDerived1(3,4,5); } } Output: I am an Overloaded Constructor with a value of 3 I am an Overloaded Constructor with a value of 4 I am an overloaded constructor of child of derived with value of z as 5 ]
  • 68. [ Code: package com.company; import javax.print.Doc; class EkClass { int a; public int getA() { return a; } EkClass(int v) { this.a = v; } public int returnone(){ return 1; } } //super keyword is used to refer to the super class of the current class, and run the constructor with arguments class DoC extends EkClass{ DoC(int c){ super(c); System.out.println("Mai ek constructor hun"); } } public class cwh_47_this_super { public static void main(String[] args) { EkClass e = new EkClass(65); DoC d = new DoC(5); System.out.println(e.getA()); } } Output: Mai ek constructor hun 65 ]
  • 69. [ Code: package com.company; //method overriding class A{ public int a; public int harry(){ return 4; } public void meth2(){ System.out.println("I am method 2 of class A"); } } class B extends A{ public void meth2(){ System.out.println("I am method 2 of class B"); //This is method overriding }// same meth2() of class A in class B so it implements its own meth2() public void meth3(){ System.out.println("I am method 3 of class B"); } } public class cwh_48_method_overriding { public static void main(String[] args) { A a = new A(); a.meth2(); B b = new B(); b.meth2(); } } Output: I am method 2 of class A I am method 2 of class B ]
  • 70. [ Code: package com.company; class Phone{ public void greet(){ System.out.println("Good Morning"); } public void on(){ System.out.println("Turning on Phone"); } } class SmartPhone extends Phone{ public void swagat(){ System.out.println("Aapka swagat hai"); } @Override public void on(){ System.out.println("Turning on SmartPhone"); } } public class cwh_49_dynamic_method_dispatch { public static void main(String[] args) { Phone obj = new SmartPhone();//Superclass reference obj can be equal to sub class object as here //SmartPhone obj = new Phone(); // will give error, opposite is not allowed obj.greet(); obj.on();// It exectutes of the object(smartphone) not of reference(phone) //This is called dynamic method dispatching } } Output: Good Morning Turning on SmartPhone ]
  • 71. [ Code: package com.company; class Phone{ public void showTime(){ System.out.println("Time is 8 am"); } public void on(){ System.out.println("Turning on Phone"); } } class SmartPhone extends Phone{ public void music(){ System.out.println("Playing music..."); } @Override public void on(){ System.out.println("Turning on SmartPhone"); } } public class cwh_49_dynamic_method_dispatch { public static void main(String[] args) { Phone obj = new SmartPhone();//Superclass reference obj can be equal to sub class object as here //SmartPhone obj = new Phone(); // will give error, opposite is not allowed obj.showTime(); obj.on();// It exectutes of the object(smartphone) not of reference(phone) //This is called dynamic method dispatching //obj.music(); // is not allowed } } Output: Time is 8 am Turning on SmartPhone ]
  • 72. [ Code: package com.company; import java.util.Random; import java.util.Scanner; class Game{ public int number; public int inputNumber; public int noOfGuesses; public int getNoOfGuesses() { return noOfGuesses; } public void setNoOfGuesses(int noOfGuesses) { this.noOfGuesses = noOfGuesses; } Game(){ Random rand = new Random(); this.number = rand.nextInt(100); } void takeUserInput(){ System.out.println("Guess the number"); Scanner sc = new Scanner(System.in); inputNumber= sc.nextInt(); } boolean isCorrectNumber(){ 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; } } public class cwh_43_exercise3 { public static void main(String[] args) { /* create a class Game which allows user to play "Guess the Number" game once.Game should have the following methods- 1. Constructor to generate the random number 2. takeUserInput() to take user input of a number 3. isCorrectNumber() i=to check whether entered number is correct 4. getter and setters for no. of guesses Use properties such as noOfGuesses(int) to get the task done */ Game g = new Game(); boolean b = false; while(!b) { g.takeUserInput(); b = g.isCorrectNumber(); System.out.println(b); } } }
  • 73. Output: Guess the number 2 Too low... false Guess the number 5 Too low... false Guess the number 8 True ]
  • 74. [ Code: package com.company; //create a class circle and use inheritance to create another class cylinder from it class Circle{ Circle(){ System.out.println("I am non parameter of circle"); } Circle(int r){ System.out.println("I am Circle Parameterized constructor"); this.radius = r; } public int radius; public double area(){ return Math.PI*this.radius*this.radius; } } class Cylinder extends Circle{ public int height; Cylinder(int r, int h) { //Super keyword means only super's words will be listened to first, so the //default constructor will not be run, what super says will be run first super(r); System.out.println("I am Cylinder Parameterized constructor"); this.height=h; } public double volume(){ return Math.PI*this.radius*this.radius*this.height; } } public class cwh_52_chap10ps { public static void main(String[] args) { Circle obj = new Circle(12); System.out.println("Area is: "); System.out.println(obj.area()); Cylinder obj2 = new Cylinder(2,3); System.out.println("Volume is: "); System.out.println(obj2.volume()); } } Output: I am Circle Parameterized constructor Area is: 452.3893421169302 I am Circle Parameterized constructor I am Cylinder Parameterized constructor Volume is: 37.69911184307752 ]
  • 75. [ Code: package com.company; //Abstract class is a class jiski sahayata lekar aur classes aap bana te ho //Abstract class ek class hota nhi hai, lekin vo ek zariya hai, Child2 jaise concrete class banane ka // Abstract classes cant have objects //Analogy - Parent2 class is saying to his Child2 and Child3 classes, bacchon, please use greet() abstract //anyway you want or you yourself become a standard that is parent abstract class Parent2{ // 1 abstract method makes whole class abstract. //Must declare the whole class as abstract using abstract keyword public Parent2(){ System.out.println("Mai base2 ka constructor hun"); } public void sayHello(){ System.out.println("Hello"); } abstract public void greet(); abstract public void greet2(); } class Child2 extends Parent2{ @Override public void greet(){ System.out.println("Good Morning"); } @Override public void greet2(){ System.out.println("Good Afternoon"); } } abstract class Child3 extends Parent2{ public void th(){ System.out.println("I am Good"); } } public class cwh_53_abstract { public static void main(String[] args) { Child2 c = new Child2(); // Parent2 p = new Parent2(); ---- Error // Child3 c3 = new Child3(); ---- Error } } Output: Mai base2 ka constructor hun ]
  • 76. [ Code: package com.company; interface Bicycle{ int a = 45; // Attribute or property void applyBrake(int decrement); void speedUp(int increment); } interface HornBicycle{ public int b = 45; void blowHornK3g(); void blowHornmhn(); } class AvonCycle implements Bicycle,HornBicycle{ public int b = 5; void blowHorn(){ System.out.println("Pee pee poo poo"); } //ALWAYS the methods of interface should have public access modifiers public void applyBrake(int decrement){ System.out.println("Applying brake..."); } public void speedUp(int increment){ System.out.println("Speeding Up..."); } public void blowHornK3g(){ System.out.println("Kabhi kushi kabhi gum pee pee pee pee"); } public void blowHornmhn(){ System.out.println("Mai hun na po po po po"); } } public class cwh_54_Interfaces { public static void main(String[] args) { AvonCycle cycleAdhi = new AvonCycle(); cycleAdhi.applyBrake(1); //You can create property in Interfaces System.out.println(cycleAdhi.a); //You can not modify the properties in Interfaces as they are final // cycleAdhi.a = 454; ---> gives error cycleAdhi.blowHornK3g(); cycleAdhi.blowHornmhn(); System.out.println(cycleAdhi.b); } } Output: Applying brake... 45 Kabhi kushi kabhi gum pee pee pee pee Mai hun na po po po po 5 ]
  • 77. [ Code: package com.company; interface MyCamera { void takeSnap(); void recordVideo(); private void greet(){ System.out.println("Good Morning"); } default void record4KVideo() { greet(); // private methods in interface cannot be directly used by class but, using default methods // we can use the private method System.out.println("Recording 4K..."); } //default was introduced as if we add 1 abstract method in interface, all existin classes implementing //the interface will fail, and we have to correct all of them, so we add //default method so that we dont need to edit ALL existing classes using the interface } interface MyWifi{ String [] getNetworks(); void connectToNetwork(String network); } class MyCellPhone{ void callnumber(int phoneNumber){ System.out.println("Calling"+ phoneNumber); } void pickCall(){ System.out.println("Connecting..."); } public void takeSnap(){ System.out.println("Taking snap"); } } class MySmartPhone extends MyCellPhone implements MyWifi, MyCamera{ public void takeSnap(){ System.out.println("Taking snap"); } public void recordVideo(){ System.out.println("Taking snap"); } @Override public void record4KVideo(){ System.out.println("Taking Snap and recording 4K Video"); // can comment this override code to get another output } public String [] getNetworks() { System.out.println("Getting List of Networks"); String [] networkList = {"Adhi", "Jake"}; return networkList; } public void connectToNetwork(String network){ System.out.println("Connecting.."+ network); } } public class cwh_57_default_methods { public static void main(String[] args) { MySmartPhone ms = new MySmartPhone();
  • 78. ms.record4KVideo(); //Default method String [] ar = ms.getNetworks(); for (String item : ar){ System.out.println(item); } } } //Two types of methods - static methods and default methods // Static method is not associated with object, it is only associated with class or interface Output: Taking Snap and recording 4K Video Getting List of Networks Adhi Jake ] [ Code: package com.company; //To follow the Do Not Repeat Yourself(DRY) principle, we follow Inheritance in Interfaces interface sampleInterface{ void meth1(); void meth2(); } interface childSampleInterface extends sampleInterface{ void meth3(); void meth4(); } class MySampleClass implements childSampleInterface{ public void meth1(){ System.out.println("meth1"); } public void meth2(){ System.out.println("meth2"); } public void meth3(){ System.out.println("meth3"); } public void meth4(){ System.out.println("meth4"); } } public class cwh_58_inheritance_interfaces { public static void main(String[] args) { MySampleClass obj = new MySampleClass(); obj.meth1(); obj.meth2(); obj.meth3(); obj.meth4(); } }
  • 79. Output: meth1 meth2 meth3 meth4 ] [ Code: package com.company; //Polymorphism interface MyCamera2{ void takeSnap(); void recordVideo(); private void greet(){ System.out.println("Good Morning"); } default void record4KVideo() { greet(); // private methods in interface cannot be directly used by class but, using default methods // we can use the private method System.out.println("Recording 4K..."); } //default was introduced as if we add 1 abstract method in interface, all existin classes implementing //the interface will fail, and we have to correct all of them, so we add //default method so that we dont need to edit ALL existing classes using the interface } interface MyWifi2{ String [] getNetworks(); void connectToNetwork(String network); } class MyCellPhone2{ void callnumber(int phoneNumber){ System.out.println("Calling"+ phoneNumber); } void pickCall(){ System.out.println("Connecting..."); } public void takeSnap(){ System.out.println("Taking snap"); } } class MySmartPhone2 extends MyCellPhone2 implements MyWifi2, MyCamera2{ public void takeSnap(){ System.out.println("Taking snap"); } public void recordVideo(){ System.out.println("Taking snap"); } @Override public void record4KVideo(){ System.out.println("Taking Snap and recording 4K Video"); // can comment this override code to get another output
  • 80. } public String [] getNetworks() { System.out.println("Getting List of Networks"); String [] networkList = {"Adhi", "Jake"}; return networkList; } public void connectToNetwork(String network){ System.out.println("Connecting.."+ network); } } public class cwh_59_polymorphism { public static void main(String[] args) { MyCamera2 cam1 = new MySmartPhone2(); //This is a SmartPhone but use it as a Camera //cam1.getNetworks(); ----> not allowed cam1.record4KVideo(); MySmartPhone2 s = new MySmartPhone2(); s.getNetworks(); s.recordVideo(); s.callnumber(23453); } } Output: Taking Snap and recording 4K Video Getting List of Networks Taking snap Calling23453 ]
  • 81. [ Code: package com.company; //create an abstract class Pen with abstract methods write() and refill() as abstract methods //create a concrete class FountainPen with additional method changeNib() abstract class Pen{ abstract void write(); abstract void refill(); } class FountainPen extends Pen{ void write(){ System.out.println("Writing"); } void refill(){ System.out.println("Refill"); } void changeNib(){ System.out.println("Changing the Nib"); } } public class cwh_60_ch11ps { public static void main(String[] args) { FountainPen pen = new FountainPen(); pen.changeNib(); } } Output: Changing the Nib ]
  • 82. [ Code: package com.company; //create class Monkey with jump() and bite() methods. Create a class Human which inherits this class Monkey //and implements BasicAnimal interface with eat() and sleep() methods class Monkey{ void jump(){ System.out.println("Jumping..."); } void bite(){ System.out.println("Biting..."); } } interface BasicAnimal{ void eat(); void sleep(); } class Human extends Monkey implements BasicAnimal{ void speak(){ System.out.println("Hello !"); } public void eat(){ System.out.println("Eating..."); } public void sleep(){ System.out.println("Sleeping..."); } } public class cwh_60_ch11ps { public static void main(String[] args) { Human Adhi = new Human(); Adhi.eat(); Adhi.sleep(); Adhi.speak(); Adhi.bite(); Adhi.jump(); } } Output: Eating... Sleeping... Hello ! Biting... Jumping... ]
  • 83. [ Code: package com.company; //create class Monkey with jump() and bite() methods. Create a class Human which inherits this class Monkey //and implements BasicAnimal interface with eat() and sleep() methods // And demonstrate polymorphism class Monkey{ void jump(){ System.out.println("Jumping..."); } void bite(){ System.out.println("Biting..."); } } interface BasicAnimal{ void eat(); void sleep(); } class Human extends Monkey implements BasicAnimal{ void speak(){ System.out.println("Hello !"); } public void eat(){ System.out.println("Eating..."); } public void sleep(){ System.out.println("Sleeping..."); } } public class cwh_60_ch11ps { public static void main(String[] args) { Human Adhi = new Human(); Adhi.eat(); Adhi.sleep(); Adhi.speak(); Adhi.bite(); Adhi.jump(); Monkey m1 = new Human(); // m1.speak(); // ---> gives error, cannot use speak() method as // reference is Monkey which does not have speak() method m1.jump(); m1.bite(); BasicAnimal lovish = new Human(); //lovish.speak(); ---> gives error and this demonstrates polymorphism } }
  • 85. [ Code: package com.company; class Library{ String []books; int no_of_books = 0; Library(){ this.books = new String[100]; this.no_of_books=0; } void addBook(String book){ this.books[no_of_books]= book; no_of_books++; System.out.println(book + " has been added!"); } void showAvailableBooks(){ System.out.println("Available Books are..."); for(String item : this.books){ if(item == null){ continue; } System.out.println("*" + item); } } void issueBook(String book){ for (int i =0; i<this.books.length; i++){ if(this.books[i].equals(book)){ System.out.println("This book has been issued!"); this.books[i]= null; return; } } System.out.println("This book does not exist!"); } void returnBook(String book){ addBook(book); } } public class cwh_51_exercise4 { public static void main(String[] args) { //You have to implement a class library using Java Class Library //Methods: issueBook, returnBook, showAvailableBooks //Properties: array to store the available books //Array to store issued books Library centralLibrary = new Library(); centralLibrary.addBook("Think and Grow Rich!"); centralLibrary.addBook("Ikigai"); centralLibrary.addBook("Atomic Habits"); centralLibrary.showAvailableBooks(); centralLibrary.issueBook("Atomic Habits"); centralLibrary.showAvailableBooks();; centralLibrary.returnBook("Atomic Habits"); centralLibrary.showAvailableBooks(); } }
  • 86. Output: Think and Grow Rich! has been added! Ikigai has been added! Atomic Habits has been added! Available Books are... *Think and Grow Rich! *Ikigai *Atomic Habits This book has been issued! Available Books are... *Think and Grow Rich! *Ikigai Atomic Habits has been added! Available Books are... *Think and Grow Rich! *Ikigai *Atomic Habits ]
  • 87. [ Code: package com.company; //Access modifiers access in same class illustration class C1{ public int x = 5; protected int y = 45; int z = 7; private int a = 73; public void meth1(){ System.out.println(x); System.out.println(y); System.out.println(z); System.out.println(a); } } public class cwh_66_access_modifiers { public static void main(String[] args) { C1 c = new C1(); c.meth1(); } } Output: 5 45 7 73 ]
  • 88. [ Code: package com.company; //Access modifiers access in same package illustration class C1{ public int x = 5; protected int y = 45; int z = 7; private int a = 73; public void meth1(){ System.out.println(x); System.out.println(y); System.out.println(z); System.out.println(a); } } public class cwh_66_access_modifiers { public static void main(String[] args) { C1 c = new C1(); System.out.println(c.x); System.out.println(c.y); System.out.println(c.z); //System.out.println(c.a); --> gives error as private access } } Output: 5 45 7 ]
  • 89. [ Code: package com.company; //Difference b/w concurrency and parallelism is similar to difference b/w parameters and arguments // Concurrency means, you are managing multiple tasks overall, but at a time you are doing only one task //Parallelism means actually both tasks are happening together simultaneously //Multithreading in java follows concurrency //We use Threads to achieve multitasking within a process class MyThread1 extends Thread{ @Override public void run(){ int i = 0; while(i<5){ System.out.println("My thread is running"); System.out.println("I am happy!"); i++; } } } class MyThread2 extends Thread{ @Override public void run(){ int i = 0; while(i<5){ System.out.println("Thread2 is good"); System.out.println("I am sad"); i++; } } } public class cwh_70 { public static void main(String[] args) { MyThread1 t1 = new MyThread1(); MyThread2 t2 = new MyThread2(); t1.start(); t2.start();// start() is method to run threads } }
  • 90. Output: My thread is running Thread2 is good I am happy! My thread is running I am happy! My thread is running I am happy! My thread is running I am happy! My thread is running I am happy! I am sad Thread2 is good I am sad Thread2 is good I am sad Thread2 is good I am sad Thread2 is good I am sad ]
  • 91. [ Code: package com.company; //Runnable is an in built interface in Thread class MyThreadRunnable1 implements Runnable{ public void run(){ System.out.println("I am a thread1 not a threat1"); } } class MyThreadRunnable2 implements Runnable{ public void run(){ System.out.println("I am a thread2 not a threat2"); } } public class cwh_71_runnable { public static void main(String[] args) { MyThreadRunnable1 bullet1 = new MyThreadRunnable1(); MyThreadRunnable2 bullet2 = new MyThreadRunnable2(); Thread gun1 = new Thread(bullet1); Thread gun2 = new Thread(bullet2); gun1.start(); gun2.start(); } } Output: I am a thread1 not a threat1 I am a thread2 not a threat2 ]
  • 92. [ Code: package com.company; //Thread is a class //Refer to notes for Constructors in java types //start() is for starting Thread class MyThr extends Thread{ public MyThr(String name){ super(name); // as there is already a constructor in Thread that uses name } public void run(){ int i = 34; System.out.println("Thank you"); } } public class cwh_73_thread_constructor { public static void main(String[] args) { MyThr t = new MyThr("Adhi"); MyThr t2 = new MyThr("M"); t.start(); System.out.println("The id of this thread is "+ t.getId()); System.out.println("The name of the thread is "+ t.getName()); System.out.println("The id of t2 is "+ t.getId()); System.out.println("The name of t2 is "+ t.getName()); } } Output: The id of this thread is 20 The name of the thread is Adhi The id of t2 is 20 The name of t2 is Adhi Thank you ]
  • 93. [ Code: package com.company; class MyThr1 extends Thread{ public MyThr1(String name){ super(name); // as there is already a constructor in Thread that uses name } public void run(){ int i = 34; System.out.println("Thank you " + this.getName()); } } public class cwh_74_thread_priorities { public static void main(String[] args) { MyThr1 t1 = new MyThr1("Adhi1"); MyThr1 t2 = new MyThr1("Adhi2"); MyThr1 t3 = new MyThr1("Adhi3"); MyThr1 t4 = new MyThr1("Adhi4"); MyThr1 t5 = new MyThr1("Adhi5"); t1.start(); t2.start(); t3.start(); t4.start(); t5.start(); } } Output: Thank you Adhi1 Thank you Adhi2 Thank you Adhi3 Thank you Adhi4 Thank you Adhi5 ]
  • 94. [ Code: package com.company; //Thread Priorities class MyThr1 extends Thread{ public MyThr1(String name){ super(name); // as there is already a constructor in Thread that uses name } public void run(){ int i = 34; System.out.println("Thank you " + this.getName()); } } public class cwh_74_thread_priorities { public static void main(String[] args) { MyThr1 t1 = new MyThr1("Adhi1"); MyThr1 t2 = new MyThr1("Adhi2"); MyThr1 t3 = new MyThr1("Adhi3"); MyThr1 t4 = new MyThr1("Adhi4"); MyThr1 t5 = new MyThr1("Adhi5"); t5.setPriority(Thread.MAX_PRIORITY); //max priority t1.setPriority(Thread.MIN_PRIORITY); //min priority t1.start(); t2.start(); t3.start(); t4.start(); t5.start(); } } Output: Thank you Adhi5 Thank you Adhi2 Thank you Adhi3 Thank you Adhi4 Thank you Adhi1 ]
  • 95. [ Code: package com.company; class MyNewThr1 extends Thread{ public void run(){ int i = 0; while(i<8){ System.out.println("Thank you"); i++; } } } class MyNewThr2 extends Thread{ public void run(){ int j = 0; while(j<8){ System.out.println("Thank you2"); j++; } } } public class cwh_75_thread_method { public static void main(String[] args) { MyNewThr1 t1 = new MyNewThr1(); MyNewThr2 t2 = new MyNewThr2(); t1.start(); try{ //put it in try-catch block t1.join(); //Join can be used if you want it like till t1 doesnt end, t2 doesnt start } catch(Exception e){ System.out.println(e); } t2.start(); } } Output: Thank you Thank you Thank you Thank you Thank you Thank you Thank you Thank you Thank you2
  • 96. Thank you2 Thank you2 Thank you2 Thank you2 Thank you2 Thank you2 Thank you2 ]
  • 97. [ Code: package com.company; //Thread Method - Interrupted Method class MyNewThr1 extends Thread{ public void run(){ int i = 0; while(i<8){ System.out.println("Thank you"); try { Thread.sleep(8); } catch (InterruptedException e) { //Interrupted Method throw new RuntimeException(e); } i++; } } } class MyNewThr2 extends Thread{ public void run(){ int j = 0; while(j<8){ System.out.println("Thank you2"); j++; } } } public class cwh_75_thread_method { public static void main(String[] args) { MyNewThr1 t1 = new MyNewThr1(); MyNewThr2 t2 = new MyNewThr2(); t1.start(); t2.start(); } } Output: Thank you Thank you2 Thank you2 Thank you2 Thank you2 Thank you2 Thank you2 Thank you2 Thank you2 Thank you
  • 98. Thank you Thank you Thank you Thank you Thank you Thank you ]
  • 99. [ Code: package com.company; //write a program to print "good morning" and "welcome" continuously till an end point in Java using Threads class Practice13a extends Thread{ public void run(){ int i = 0; while(i<8){ System.out.println("good morning"); i++; } } } class Practice13b extends Thread{ public void run(){ int i = 0; while(i<8){ System.out.println("Welcome"); i++; } } } public class cwh_76_practice13 { public static void main(String[] args) { Practice13a p1 = new Practice13a(); Practice13b p2 = new Practice13b(); p1.start(); p2.start(); } } Output: good morning good morning good morning good morning good morning good morning good morning good morning Welcome Welcome Welcome
  • 101. [ Code: package com.company; //write a program to print "good morning" and "welcome" continuously till an end point in Java using Threads //Then add sleep method to this, and delay the execution by 200ms of the Welcome thread class Practice13a extends Thread{ public void run(){ int i = 0; while(i<8){ System.out.println("good morning"); i++; } } } class Practice13b extends Thread{ public void run(){ int i = 0; while(i<8){ try { Thread.sleep(200); } catch (InterruptedException e) { throw new RuntimeException(e); } System.out.println("Welcome"); i++; } } } public class cwh_76_practice13 { public static void main(String[] args) { Practice13a p1 = new Practice13a(); Practice13b p2 = new Practice13b(); p1.start(); p2.start(); } } Output: good morning good morning good morning good morning good morning good morning good morning good morning
  • 103. [ Code: package com.company; //write a program to print "good morning" and "welcome" continuously till an end point in Java using Threads //Then add sleep method to this, and delay the execution by 200ms of the Welcome thread //Then Demonstrate setPriority() and getPriority() methods in Java class Practice13a extends Thread{ public void run(){ int i = 0; while(i<8){ System.out.println("good morning"); i++; } } } class Practice13b extends Thread{ public void run(){ int i = 0; while(i<8){ try { Thread.sleep(200); } catch (InterruptedException e) { throw new RuntimeException(e); } System.out.println("Welcome"); i++; } } } public class cwh_76_practice13 { public static void main(String[] args) { Practice13a p1 = new Practice13a(); Practice13b p2 = new Practice13b(); p1.setPriority(6); p2.setPriority(9); System.out.println(p1.getPriority()); System.out.println(p2.getPriority()); //p1.start(); //p2.start(); //If setPriority() is not done, they have normal priority equal //NORM_PRIORITY value is 5 } } Output: 6 9 ]
  • 104. [ Code: package com.company; //How do you get the state of a thread in java? class Practice13a extends Thread{ public void run(){ int i = 0; while(i<8){ System.out.println("good morning"); i++; } } } class Practice13b extends Thread{ public void run(){ int i = 0; /* while(i<8){ try { Thread.sleep(200); } catch (InterruptedException e) { throw new RuntimeException(e); } System.out.println("Welcome"); i++; }*/ } } public class cwh_76_practice13 { public static void main(String[] args) { Practice13a p1 = new Practice13a(); Practice13b p2 = new Practice13b(); p1.setPriority(6); p2.setPriority(9); System.out.println(p1.getPriority()); System.out.println(p2.getPriority()); //p1.start(); System.out.println(p2.getState()); p2.start(); System.out.println(p2.getState()); //getState() gives the state of the thread } } Output: 6 9 NEW RUNNABLE ]
  • 105. [ Code: package com.company; //How do you get reference to the current thread in Java? - using currentThread() class Practice13a extends Thread{ public void run(){ int i = 0; while(i<8){ System.out.println("good morning"); i++; } } } class Practice13b extends Thread{ public void run(){ int i = 0; while(i<8){ try { Thread.sleep(200); } catch (InterruptedException e) { throw new RuntimeException(e); } System.out.println("Welcome"); i++; } } } public class cwh_76_practice13 { public static void main(String[] args) { Practice13a p1 = new Practice13a(); Practice13b p2 = new Practice13b(); p1.setPriority(6); p2.setPriority(9); System.out.println(p1.getPriority()); System.out.println(p2.getPriority()); //p1.start(); // System.out.println(p2.getState()); p2.start(); //System.out.println(p2.getState()); System.out.println(Thread.currentThread()); } } Output: 6 9 Thread[#1,main,5,main] Welcome Welcome Welcome
  • 106. Welcome Welcome Welcome Welcome Welcome ] [ Code: package com.company; public class cwh_78_errors { public static void main(String[] args) { //Write a program to print all prime numbers between 1 to 10 System.out.println(2); for(int i=1; i<5; i++){ System.out.println(2*i+1); //this is logical error as it prints odd numbers and not prime numbers } } } Output: 2 3 5 7 9 ] [ Code: package com.company; //Arithmetic exception example public class cwh_80_try { public static void main(String[] args) { int a = 6000; int b = 0; int c = a/b; System.out.println("the result is "+ c); } }
  • 107. Output: Exception in thread "main" java.lang.ArithmeticException: / by zero at com.company.cwh_80_try.main(cwh_80_try.java:7) ] [ Code: package com.company; //Solving Arithmetic Exception of division by zero using Try catch block public class cwh_80_try { public static void main(String[] args) { int a = 6000; int b = 0; try{ int c = a/b; System.out.println("the result is "+ c); }catch(Exception e){ System.out.println("We couldnt divide because of "); System.out.println(e); } } } Output: We couldnt divide because of java.lang.ArithmeticException: / by zero ]
  • 108. [ Code: package com.company; //How to hancle specific exceptions. //Handling specific type of exceptions import java.util.Scanner; public class cwh_81 { public static void main(String[] args) { int [] marks = new int[3]; marks[0] = 7; marks[1] = 56; marks[2] = 6; Scanner sc = new Scanner(System.in); System.out.println("Enter the array index: "); int ind = sc.nextInt(); System.out.println("Enter the number with which you want to divide the value with: "); int number = sc.nextInt(); try{ System.out.println("The value of the value at index entered is : "+ marks[ind]); System.out.println("The array of array-value/number is : "+ marks[ind]/number); }catch(Exception e){ System.out.println("Some Exception error occurred!"); System.out.println(e); } } } Output: Enter the array index: 1 Enter the number with which you want to divide the value with: 23 The value of the value at index entered is : 56 The array of array-value/number is : 2 ]
  • 109. [ Code: package com.company; //How to hancle specific exceptions. //Handling specific type of exceptions import java.util.Scanner; public class cwh_81 { public static void main(String[] args) { int [] marks = new int[3]; marks[0] = 7; marks[1] = 56; marks[2] = 6; Scanner sc = new Scanner(System.in); System.out.println("Enter the array index: "); int ind = sc.nextInt(); System.out.println("Enter the number with which you want to divide the value with: "); int number = sc.nextInt(); try{ System.out.println("The value of the value at index entered is : "+ marks[ind]); System.out.println("The array of array-value/number is : "+ marks[ind]/number); }catch(ArithmeticException e){ System.out.println("Some Exception error occurred!"); System.out.println(e); }catch(ArrayIndexOutOfBoundsException e){ System.out.println("Some Exception error occurred!"); System.out.println(e); }catch(Exception e){ System.out.println("Some Exception error occurred!"); System.out.println(e); } } } Output: Enter the array index: 4 Enter the number with which you want to divide the value with: 2 Some Exception error occurred! java.lang.ArrayIndexOutOfBoundsException: Index 4 out of bounds for length 3 ]
  • 110. [ Code: package com.company; //nested try catch have levels public class cwh_82_nested_try_catch { public static void main(String[] args) { int [] marks = new int[5]; marks[0] = 7; marks[1] = 56; marks[2] = 6; try{ System.out.println("We are in try level 1"); try{ System.out.println(marks[9]); }catch(ArrayIndexOutOfBoundsException e){ System.out.println("Sorry this index does not exist"); System.out.println("Exception in level 2"); } }catch(Exception e) { System.out.println("Exception in level 1"); } } } Output: We are in try level 1 Sorry this index does not exist Exception in level 2 ]
  • 111. [ Code: package com.company; //nested try catch have levels import java.util.Scanner; public class cwh_82_nested_try_catch { public static void main(String[] args) { int [] marks = new int[5]; marks[0] = 7; marks[1] = 56; marks[2] = 6; Scanner sc = new Scanner(System.in); System.out.println("Enter the value of index: "); int ind = sc.nextInt(); try{ System.out.println("We are in try level 1"); try{ System.out.println(marks[ind]); } catch(ArrayIndexOutOfBoundsException e){ System.out.println("Sorry this index does not exist"); System.out.println("Exception in level 2"); } } catch(Exception e) { System.out.println("Exception in level 1"); } } } Output: Enter the value of index: 1 We are in try level 1 56 ]
  • 112. [ Code: package com.company; //nested try catch have levels import org.w3c.dom.ls.LSOutput; import java.util.Scanner; public class cwh_82_nested_try_catch { public static void main(String[] args) { int[] marks = new int[5]; marks[0] = 7; marks[1] = 56; marks[2] = 6; Scanner sc = new Scanner(System.in); boolean flag = true; while (flag) { System.out.println("Enter the value of index: "); int ind = sc.nextInt(); try { System.out.println("We are in try level 1"); try { System.out.println(marks[ind]); flag = false; } catch (ArrayIndexOutOfBoundsException e) { System.out.println("Sorry this index does not exist"); System.out.println("Exception in level 2"); } } catch (Exception e) { System.out.println("Exception in level 1"); } } System.out.println("Thank you for using the program"); } } Output: Enter the value of index: 1 We are in try level 1 56 Thank you for using the program ]
  • 113. [ Code: package com.company; import java.util.Scanner; class MyException extends Exception{ @Override public String toString(){ return super.toString() + " I am toString()"; } public String getMessage(){ return super.getMessage() + " I am getMessage()"; } } public class cwh_83_exception_class { public static void main(String[] args) throws MyException { int a; Scanner sc = new Scanner(System.in); System.out.println("enter a: "); a = sc.nextInt(); if (a<9){ try { throw new MyException(); }catch(Exception e){ System.out.println(e.getMessage()); } } } } Output: enter a: 4 null I am getMessage() ]
  • 114. [ Code: package com.company; //Harry made a function. Shivam tries to use it. Harry can warn shivam that there is a possibilty of exception //Shivam should accrodingly create a try catch block public class cwh_84_throw_throws { public static int divide(int a, int b) throws ArithmeticException{ //Made by Harry int result = a/b; return result; } public static void main(String[] args) { //Shivam - uses divide function created by Harry try{ int c = divide(6, 0); System.out.println(c); } catch(Exception e){ System.out.println("Exception"); } } } Output: Exception ]
  • 115. [ Code: package com.company; import java.util.Scanner; class MyException extends Exception{ @Override public String toString(){ return" I am toString()"; } public String getMessage(){ return " I am getMessage()"; } } public class cwh_83_exception_class { public static void main(String[] args) throws MyException { int a; Scanner sc = new Scanner(System.in); System.out.println("enter a: "); a = sc.nextInt(); if (a<9){ try { throw new ArithmeticException("This is an Exception") ; }catch(Exception e){ System.out.println(e.getMessage()); System.out.println("Finished"); } System.out.println("Yes Finished"); } } } Output: enter a: 3 This is an Exception Finished Yes Finished ]
  • 116. [ Code: package com.company; //code in finally block is always executed no matter what even if it is an exception public class cwh_85_finally { public static void main(String[] args) { try{ int a = 5; int b = 0; int c = a/b; }catch(Exception e){ System.out.println(e); } finally { System.out.println("This is the end of program"); } } } Output: java.lang.ArithmeticException: / by zero This is the end of program ] [ Code: package com.company; //code in finally block is always executed no matter what even if it is an exception public class cwh_85_finally { public static int greet() { try { int a = 50; int b = 2; int c = a / b; return c; } catch (Exception e) { System.out.println(e); } finally { System.out.println("This is the end of program"); } return 0; } public static void main(String[] args) { int k = greet(); System.out.println(k); } }
  • 117. Output: This is the end of program 25 ] [ Code: package com.company; //code in finally block is always executed no matter what even if it is an exception public class cwh_85_finally { public static int greet() { try { int a = 50; int b = 10; int c = a / b; return c; } catch (Exception e) { System.out.println(e); } finally { System.out.println("Cleaning up resources... This is the end of program"); } return 0; } public static void main(String[] args) { int k = greet(); System.out.println(k); } } Output: Cleaning up resources... This is the end of program 5 ]
  • 118. [ Code: package com.company; //code in finally block is always executed no matter what even if it is an exception public class cwh_85_finally { public static int greet() { try { int a = 50; int b = 10; int c = a / b; return c; } catch (Exception e) { System.out.println(e); } finally { System.out.println("Cleaning up resources... This is the end of program"); } return 0; } public static void main(String[] args) { int k = greet(); System.out.println(k); int a = 7; int b = 0; while(true){ try{ System.out.println(a/b); }catch(Exception e){ System.out.println(e); break; } finally { System.out.println("I am finally value for b = " + b); } } b--; } } Output: Cleaning up resources... This is the end of program 5 java.lang.ArithmeticException: / by zero I am finally value for b = 0 ]
  • 119. [ Code: package com.company; //code in finally block is always executed no matter what even if it is an exception public class cwh_85_finally { public static int greet() { try { int a = 50; int b = 10; int c = a / b; return c; } catch (Exception e) { System.out.println(e); } finally { System.out.println("Cleaning up resources... This is the end of program"); } return 0; } public static void main(String[] args) { int k = greet(); System.out.println(k); int a = 7; int b = 0; while(true){ try{ System.out.println(a/b); }catch(Exception e){ System.out.println(e); break; } finally { System.out.println("I am finally value for b = " + b); } } b--; try{ System.out.println(50/10); }finally{ System.out.println("Yes this is final"); } } } Output: Cleaning up resources... This is the end of program 5 java.lang.ArithmeticException: / by zero I am finally value for b = 0 5 Yes this is final ]
  • 120. [ Code: package com.company; //Problem - demonstrate syntax error and logical error and runtime error public class cwh_86_ps14 { public static void main(String[] args) { // Syntax error - int a = 7 int age = 78; int year_born = 2000 - 78; //Logical error // Runtime error - System.out.println(6/0); System.out.println("SOLVED"); } } Output: SOLVED ] [ Code: package com.company; //Problem - write a Java program that prints "HaHa" during Arithmetic exception and "HeHe" durig //Illegal Argument exception public class cwh_86_ps14 { public static void main(String[] args) { try{ int a =666/9; } catch(IllegalArgumentException e){ System.out.println("HeHe"); } catch(ArithmeticException e){ System.out.println("HaHa"); } System.out.println("Finished"); } } Output: Finished ]
  • 121. [ Code: package com.company; //Problem - write a program that allows you to keep accessing the array until a valid index is given // if max retries exceed 5 then print error import java.util.Scanner; public class cwh_86_ps14 { public static void main(String[] args) { boolean flag = true; int [] marks = new int[3]; marks[0] = 7; marks[1] = 56; marks[2] = 6; Scanner sc = new Scanner(System.in); int index; int i = 0; while(flag && i<5){ try{ System.out.println("Enter index "); index = sc.nextInt(); System.out.println("The value of marks[index] is " + marks[index]); i++; break; }catch(Exception e){ System.out.println("Invalid Index"); } } } } Output: Enter index 3 Invalid Index Enter index 2 The value of marks[index] is 6 ]
  • 122. [ Code: package com.company; // ArrayList, TreeSet, Set are all part of Collection Framework import java.util.ArrayList; import java.util.Set; import java.util.TreeSet; public class cwh_89_collections { public static void main(String[] args) { // ArrayList // Set // TreeSet System.out.println("Done"); } } Output: Done ] [ Code: package com.company; //ArrayList - Advanced Java // ArrayList can be resized, can we start inserting from a particular index, // we can do things we wont be able to do with normal array import java.lang.reflect.Array; import java.util.*; public class cwh_91_arraylist { public static void main(String[] args) { ArrayList<Integer> l1 = new ArrayList<>(); l1.add(6); l1.add(7); l1.add(4); l1.add(6); l1.add(5); for(int i=0; i<l1.size(); i++){ System.out.println(l1.get(i)); //get() method is used to get ith element from arraylist } } }
  • 123. Output: 6 7 4 6 5 ] [ Code: package com.company; //ArrayList - Advanced Java // ArrayList can be resized, can we start inserting from a particular index, // we can do things we wont be able to do with normal array import java.lang.reflect.Array; import java.util.*; public class cwh_91_arraylist { public static void main(String[] args) { ArrayList<Integer> l1 = new ArrayList<>(); ArrayList<Integer> l2 = new ArrayList<>(5); l2.add(15); l2.add(18); l2.add(19); l1.add(6); l1.add(7); l1.add(4); l1.add(6); l1.add(5); l1.add(0,5); l1.addAll(l2); for(int i=0; i<l1.size(); i++){ System.out.println(l1.get(i)); //get() method is used to get ith element from arraylist } } }
  • 125. [ Code: package com.company; //ArrayList - Advanced Java // ArrayList can be resized, can we start inserting from a particular index, // we can do things we wont be able to do with normal array //All important Methods of ArrayList import java.lang.reflect.Array; import java.util.*; public class cwh_91_arraylist { public static void main(String[] args) { ArrayList<Integer> l1 = new ArrayList<>(); ArrayList<Integer> l2 = new ArrayList<>(5); l2.add(15); l2.add(18); l2.add(19); l1.add(6); l1.add(7); l1.add(4); l1.add(6); l1.add(5); l1.add(0,5); l1.addAll(l2); System.out.println(l1.contains(7)); System.out.println(l1.indexOf(7)); for(int i=0; i<l1.size(); i++){ System.out.print(l1.get(i)); //get() method is used to get ith element from arraylist System.out.print(", "); } } } Output: true 2 5, 6, 7, 4, 6, 5, 15, 18, 19, ]
  • 126. [ Code: package com.company; //ArrayList - Advanced Java // ArrayList can be resized, can we start inserting from a particular index, // we can do things we wont be able to do with normal array //All important Methods of ArrayList import java.lang.reflect.Array; import java.util.*; public class cwh_91_arraylist { public static void main(String[] args) { ArrayList<Integer> l1 = new ArrayList<>(); ArrayList<Integer> l2 = new ArrayList<>(5); l2.add(15); l2.add(18); l2.add(19); l1.add(6); l1.add(7); l1.add(4); l1.add(6); l1.add(5); l1.add(0,5); l1.addAll(l2); System.out.println(l1.contains(7)); System.out.println(l1.indexOf(7)); System.out.println(l1.lastIndexOf(6)); //l1.clear(); --> for emptying for(int i=0; i<l1.size(); i++){ System.out.print(l1.get(i)); //get() method is used to get ith element from arraylist System.out.print(", "); } } } Output: true 2 4 5, 6, 7, 4, 6, 5, 15, 18, 19, ]
  • 127. [ Code: package com.company; import java.util.ArrayDeque; public class cwh_93_arraydeque { public static void main(String[] args) { ArrayDeque<Integer> ad1 = new ArrayDeque<>(); ad1.add(6); ad1.add(56); System.out.println(ad1.getFirst()); System.out.println(ad1.getLast()); } } Output: 6 56 ] [ Code: package com.company; //Hashset in Java import java.util.HashSet; //Default initial capacity is 16 and load factor is 0.75 public class cwh_95_set { public static void main(String[] args) { HashSet<Integer> myHashSet = new HashSet<>(6, 0.5F); myHashSet.add(1); myHashSet.add(11); myHashSet.add(23); myHashSet.add(12); myHashSet.add(8); System.out.println("HashSet is :"); System.out.println(myHashSet); } } Output: HashSet is : [1, 23, 8, 11, 12] ]