BT 22032 - Unit 3 Java Programs
BT 22032 - Unit 3 Java Programs
APPLICATIONS
Course Objective
2. Bytecode
While we were using the term JDK when we learn about bytecode and JVM.
So, as the name suggests, it is a complete Java development kit that
includes everything including compiler, Java Runtime Environment
(JRE), java debuggers, java docs, etc. For the program to execute in
java, we need to install JDK on our computer in order to create,
compile and run the java program.
JDK includes JRE. JRE installation on our computers allows the java
program to run, however, we cannot compile it. JRE includes a browser,
JVM, applet support, and plugins. For running the java program, a
computer needs JRE.
5. Garbage Collector
The Classpath is the file path where the java runtime and Java
compiler look for .class files to load. By default, JDK provides many
libraries. If you want to include external libraries they should be
added to the classpath.
Advantages of Java
Platform independent: Java code can run on any platform that has
a Java Virtual Machine (JVM) installed, which means that
applications can be written once and run on any device.
Disadvantages of Java
Data types in Java are of different sizes and values that can be
stored in the variable that is made as per convenience and
circumstances to cover up all test cases. Java has two categories in
which data types are segregated
Example
Type Description Default Size Range of values
Literals
true or 8
boolean false true, false
false bits true, false
twos-
8
byte complement 0 (none)
bits -128 to 127
integer
‘a’, ‘\
u0041’, ‘\ characters representation
Unicode 16
char \u0000 101’, ‘\\’, of ASCII values
character bits
‘\’, ‘\n’,
‘β’ 0 to 255
twos-
16
short complement 0 (none)
bits -32,768 to 32,767
integer
-2,147,483,648
twos-
32
int complement 0 -2,-1,0,1,2
bits to
intger
2,147,483,647
-
twos- 9,223,372,036,854,775,808
64 -2L,-
long complement 0
bits 1L,0L,1L,2L to
integer
9,223,372,036,854,775,807
1.23e100f ,
IEEE 754
32 -1.23e-
float floating 0.0
bits 100f , .3f , upto 7 decimal digits
point
3.14F
SHORT
class Main {
public static void main(String[] args) {
short temperature;
temperature = -200;
System.out.println(temperature); // prints -200
}
}
A constant is a variable whose value cannot change once it has been assigned.
Java doesn't have built-in support for constants.
A constant can make our program more easily read and understood by others. In
addition, a constant is cached by the JVM as well as our application, so using
a constant can improve performance.
class bio {
public static void main(String[] args) {
Scanner myObj = new Scanner(System.in); // Create a Scanner
object
System.out.println("Enter username");
------------------------------------------------------
MODIFIERS
Modifier Description
public
public class Main {
public String fname = "Bio";
public String lname = "Tech";
public String email = "Students";
public int start = 20242;
}
class Second {
public static void main(String[] args) {
Main myObj = new Main();
System.out.println("Name: " + myObj.fname + " " + myObj.lname);
System.out.println("Email: " + myObj.email);
System.out.println("Year: " + myObj.start);
}
}
Private
public class Main {
private String fname = "Bio";
private String lname = "Tech";
private String email = "2022bt.com";
private int start = 2024;
import java.util.Scanner;
class Largest
{
public static void main(String args[])
{
int a,b,c;
System.out.println("Enter three integers ");
Scanner sct = new Scanner(System.in);
a = sct.nextInt();
b = sct.nextInt(); //User Input
c = sct.nextInt();
if ( a > b && a > c ) // Condition check for Largest number
System.out.println("1st number is largest.");
else if ( b > a && b > c )
System.out.println("2nd number is largest.");
else if ( c > a && c > b )
System.out.println("3rd number is largest.");
else
System.out.println("Number are not distinct.");
}
}
-------------------------------------------------------------
import java.util.Scanner;
class Factorial
{
public static void main(String args[])
{
int n,c, fact = 1;
System.out.println("Enter a number");
Scanner sct = new Scanner(System.in);
n = sct.nextInt();
if ( n < 0 )
System.out.println("Number should be non-negative.");
else
{
for ( c = 1 ; c <= n ; c++ ) // Calculating Factorial
fact = fact*c;
System.out.println("Factorial of "+n+" is = "+fact);
}
}
}
-------------------------------------------------------------------
import java.util.Scanner;
class ReverseNumber
{
public static void main(String args[])
{
int n, rev = 0;
System.out.println("Enter the number to reverse ");
Scanner sct = new Scanner(System.in);
n = sct.nextInt(); //User Input
while( n != 0 )// Reversing a Number Entered
{
rev = rev * 10;
rev = rev + n%10;
n = n/10;
}
System.out.println("Reverse of entered number is "+rev);
}
}
--------------------------------------------------------------
import java.util.*;
class ReverseString
{
public static void main(String args[])
{
String original, reverse = "";
Scanner sct = new Scanner(System.in);
System.out.println("Enter string to reverse");
original = sct.nextLine(); //String input from user
int length = original.length();
for ( int i = length - 1 ; i>= 0 ; i-- ) // Reversing the String
reverse = reverse + original.charAt(i);
System.out.println("Reverse of entered string is: "+reverse);
}
}
-----------------------------------------------------------------
import java.util.Scanner;
class SubstringsOfAString
{
public static void main(String args[])
{
String str, sub;
int i, c, length;
Scanner sct = new Scanner(System.in);
System.out.println("Enter string to print all it's substrings:");
str = sct.nextLine(); // User input
length = str.length();
System.out.println("Substrings of \""+str+"\" are :-");
for( c = 0 ; c < length ; c++ )// Calculating all the substring
possible
{
for( i = 1 ; i<= length - c ; i++ )
{
sub = str.substring(c, c+i);
System.out.println(sub);
}
}
}
}
--------------------------------------------------------
Control Statement
SWITCH CASE
public class Main {
int day = 4;
switch (day) {
case 1:
System.out.println("Monday");
break;
case 2:
System.out.println("Tuesday");
break;
case 3:
System.out.println("Wednesday");
break;
case 4:
System.out.println("Thursday");
break;
case 5:
System.out.println("Friday");
break;
case 6:
System.out.println("Saturday");
break;
case 7:
System.out.println("Sunday");
break;
int i = 0;
while (i < 5) {
System.out.println(i);
i++;
if (i == 4) {
break;
System.out.println(i);
JAVA STRINGS
String s1="Biotech";
String s2="Java";
}}
if(str.length()>0) {
str = "";
if(str.length()==0) {
class LengthExample3
// main method
System.out.print(str.charAt(str.length() - i - 1));
The length() method can also be used to find only the white spaces
present in the string. Observe the following example.
// main method
Output:
System.out.println(replaceString);
}}
System.out.println(replaceString);
}}
System.out.println(rs);
rs = rs.replace("s","h"); // Replace 's' with 'h'
System.out.println(rs);
// main method
System.out.println(str);
System.out.println(str);
Methods Description
contains() Checks whether the string contains a substring.
substring() Returns the substring of the string.
join() Joins the given strings using the delimiter.
Replaces the specified old character with the
replace()
specified new character.
Replaces all substrings matching the regex
replaceAll()
pattern.
replaceFirst() Replaces the first matching substring.
Returns the character present in the specified
charAt()
location.
getBytes() Converts the string to an array of bytes.
Returns the position of the specified character
indexOf()
in the string.
compareTo() Compares two strings in the dictionary order.
compareToIgnoreCase() Compares two strings, ignoring case differences.
trim() Removes any leading and trailing whitespaces.
format() Returns a formatted string.
split() Breaks the string into an array of strings.
toLowerCase() Converts the string to lowercase.
toUpperCase() Converts the string to uppercase.
Returns the string representation of the
valueOf()
specified argument.
toCharArray() Converts the string to a char array.
Checks whether the string matches the given
matches()
regex.
Checks if the string begins with the given
startsWith()
string.
endsWith() Checks if the string ends with the given string.
isEmpty() Checks whether a string is empty or not.
Returns the canonical representation of the
intern()
string.
Checks whether the string is equal to
contentEquals()
charSequence.
hashCode() Returns a hash code for the string.
subSequence() Returns a subsequence from the string.
// create a string
String greet = "Hello! World";
System.out.println("String: " + greet);
class Main {
public static void main(String[] args) {
// create second
String second = "Students";
System.out.println("Second String: " + second);
class Main {
public static void main(String[] args) {
// create 3 strings
String first = "AEBDGF";
String second = "AEBDGF";
String third = "JDGFTRH";
class Main {
public static void main(String[] args) {
Format Specifier
import java.util.*;
class GFG {
// + sign specifier
formatter.format("%+d", 111);
System.out.println(formatter);
// + sign specifier
formatter.format("%+d", -111);
System.out.println(formatter);
}
}
import java.util.*;
// comma Specifier
formatter = new Formatter();
formatter.format("%, d", 1000000);
System.out.println(formatter);
// comma Specifier
formatter = new Formatter();
formatter.format("%, .3f", 32659526566.4521);
System.out.println(formatter);
}
}
-----------------------
import java.util.*;
class GFG {
public static void main(String args[])
{
// left justify
formatter = new Formatter();
formatter.format("|%-20.4f|", 1234.1234);
System.out.println(formatter);
}
}
-------------------------------------------
Inheritance
Modifier Description
public The code is accessible for all classes
private The code is only accessible within the declared class
The code is only accessible in the same package. This is used when
default
you don't specify a modifier.
The code is accessible in the same package and subclasses. You will
protected
learn more about subclasses and superclasses in the Inheritance
--------------------------------------
class Employee
float salary=40000;
int bonus=10000;
-------------------------------------------------------------
Inheritance
class Bio {
String name;
System.out.println("This is Java");
}
// inherited
class Main {
svc.display();
svc.BT();
class Second {
Java Arrays
public class Main {
System.out.println(bname[0]);
----------------------------------------------
bname[0] = "Food";
System.out.println(mynum[2]);
System.out.println(bname[0]);
System.out.println(bname.length);
System.out.println(bname[i]);
System.out.println(i);
int ages[] = {20, 22, 18, 35, 48, 26, 87, 70};
sum += age;
}
int ages[] = {20, 22, 18, 35, 48, 26, 87, 70};
// Loop through the elements of the ages array to find the lowest
age
lowestAge = age;
myMethod();
myMethod("Food");
myMethod("Genomics");
myMethod("Enzymes");
myMethod("Food", 4);
myMethod("Genomics", 8);
myMethod("Enzyme", 6);
Overloading
public class Main {
return x + y;
return x + y;
Separators
public class Main {
{ // This is a block
int x = 100;
System.out.println(x);
System.out.println(myNumbers[1][2]);
Interfaces
interface Gene {
System.out.println("breast cancer");
class Main {
geno.gene1();
geno.disease();
}
------------------------------------------------------------
interface Bio {
System.out.println("BT22032");
class Main {
myclass.dept();
myclass.course();
interface Polygon {
class Main{
r1.getArea(5, 6);
r2.getArea(10, 16);
Java Applets
The applet can create a graphical user interface after a user gets
an applet. It has restricted access to resources so that complicated
computations can be carried out without adding the danger of viruses
or infringing data integrity.
Drawback of Applet
1. Applet is initialized.
2. Applet is started.
3. Applet is painted.
4. Applet is stopped.
5. Applet is destroyed.
java.applet.Applet class
import java.awt.*;
import java.applet.*;
public class AppletTest extends Applet
{
public void init()
{
//initialization
}
public void start()
{
//start or resume execution
}
public void stop()
{
//suspend execution
{
public void destroy()
{
//perform shutdown activity
}
public void paint (Graphics g)
{
//display the content of window
}
}
=====================================================================
import java.util.Scanner;
class SwapNumbers
{
public static void main(String args[])
{
int z, y, temp, b;
System.out.println("Enter z and y");
Scanner sct = new Scanner(System.in); //User inputs two numbers
z = sct.nextInt(); //User inputs two numbers
y = sct.nextInt();
System.out.println("Before Swapping\nz = "+z+"\ny = "+y);
temp = z; //Swapping is done
z = y;
y = temp;
b = z;
System.out.println("After Swapping z = "+z+"\ny = "+y);
System.out.println("B value is" + b);
}
}
---------------------------------------------
class Main {
public static void main(String[] args) {
// create a string
String greet = "Hello! World";
System.out.println("String: " + greet);
// create second
String second = "Programming";
System.out.println("Second String: " + second);
class Main {
public static void main(String[] args) {
// create 3 strings
String first = "java programming";
String second = "java programming";
String third = "python programming";
class Main {
public static void main(String[] args) {
// create 3 strings
String first = "AEBCDGA";
String second = "BDEFGS";
String third = "AEBCDGA";
// compare first and second strings
boolean result1 = first.equals(second);
boolean result3 = second.equals(third);
System.out.println("Strings first and second are equal: " +
result1);
System.out.println("Whether String Second & Third is equal: \n" +
result3);
// compare first and third strings
boolean result2 = first.equals(third);
-----------------------------------------------------------------
class bio {
public static void main(String[] args) {
Scanner myObj = new Scanner(System.in); // Create a Scanner
object
System.out.println("Enter username");
-----------------------------------------------------------------
class variablescope
{
public static void main(String args[])
{
int x;
for (x = 10; x > 4; x--)
{
System.out.println(x);
}
System.out.println(x+1);
}
}
import java.util.Scanner;
class SwapNumbers
{
public static void main(String args[])
{
int z, y, temp, b;
System.out.println("Enter z and y");
Scanner sct = new Scanner(System.in); //User inputs two numbers
z = sct.nextInt(); //User inputs two numbers
y = sct.nextInt();
System.out.println("Before Swapping\nz = "+z+"\ny = "+y);
temp = z; //Swapping is done
z = y;
y = temp;
b = z;
System.out.println("After Swapping z = "+z+"\ny = "+y);
System.out.println("B value is" + b);
}
-----------------------------------------------------------------
import java.util.Scanner;
class Largest
{
public static void main(String args[])
{
int a,b,c;
System.out.println("Enter three integers ");
Scanner sct = new Scanner(System.in);
a = sct.nextInt();
b = sct.nextInt(); //User Input
c = sct.nextInt();
if ( a > b && a > c ) // Condition check for Largest number
System.out.println("1st number is largest.");
else if ( b > a && b > c )
System.out.println("2nd number is largest.");
else if ( c > a && c > b )
System.out.println("3rd number is largest.");
else
System.out.println("Number are not distinct.");
}
}
---------------------------------------------------------------
import java.util.Scanner;
class SubstringsOfAString
{
public static void main(String args[])
{
String str, sub;
int i, c, length;
Scanner sct = new Scanner(System.in);
System.out.println("Enter the Gene to print all it's substrings:");
str = sct.nextLine(); // User input
length = str.length();
System.out.println("Length" + length);
System.out.println("Substrings of \""+str+"\" are :-");
for( c = 0 ; c < length ; c++ )// Calculating all the substring
possible
{
//for( i = 1 ; i<= length - c ; i++ )
//{
sub = str.substring(c, c+1);
System.out.println(sub);
//}
}
}
}
---------------------------------------------------------------
Output
Enter number of elements 5
Enter 5 integers 8 9 7 5 0
Enter value to find 5
5 present at location 4.
The binary search is quick and is used in sorted array. The binary
search starts the element search from middle of the array and proceeds
further up or down the array depending on the mid value of the array.
import java.util.Scanner;
class BinarySearch
{
public static void main(String args[])
{
int c, first, last, middle, n, search, array[];
Scanner sct = new Scanner(System.in);
System.out.println("Enter number of elements");
n = sct.nextInt();
array = new int[n];
System.out.println("Enter " + n + " integers");
for (c = 0; c < n; c++)
{
array[c] = sct.nextInt();
}
System.out.println("Enter value to find");
search = sct.nextInt();
first = 0; // Basic binary search
last = n - 1;
middle = (first + last)/2;
while( first <= last )
{
if ( array[middle] < search )
first = middle + 1;
else if ( array[middle] == search )
{
System.out.println(search + " found at location " + (middle + 1) +
".");
break;
}
else
{
last = middle - 1;
}
middle = (first + last)/2;
if ( first > last ){
System.out.println(search + " is not present in the list.\n");
}
}
}
Output
Enter 5 integers 3 5 7 8 9
8 present at location 4.