0% found this document useful (0 votes)
34 views

JAVA Practical SS 1 To 18

The document contains code snippets demonstrating the use of various Java programming concepts like if-else statements, switch-case statements, loops (for, while, do-while), operators, constructors, string methods, and type casting. Specifically, it shows: 1) An if statement checking if a number is less than 0 and printing accordingly. 2) Examples of logical operators like &&, || and !. 3) A switch-case statement checking the size of a number and printing the corresponding size. 4) Examples of for, while and do-while loops for printing text multiple times. 5) Demonstrations of implicit and explicit type casting between primitive types. 6) Usage of default

Uploaded by

aishu.chemate01
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
34 views

JAVA Practical SS 1 To 18

The document contains code snippets demonstrating the use of various Java programming concepts like if-else statements, switch-case statements, loops (for, while, do-while), operators, constructors, string methods, and type casting. Specifically, it shows: 1) An if statement checking if a number is less than 0 and printing accordingly. 2) Examples of logical operators like &&, || and !. 3) A switch-case statement checking the size of a number and printing the corresponding size. 4) Examples of for, while and do-while loops for printing text multiple times. 5) Demonstrations of implicit and explicit type casting between primitive types. 6) Usage of default

Uploaded by

aishu.chemate01
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 54

Practical : 3

If Statement
Program Code: 1
class IF Statement {
Public static void main ( String [] args ) {
int number =10;
// Checks if number is less than 0 if (number<0) {
System.out.println(“The number is negative”);
}
System.out.println(“Statement outside if block”);
}
}

Output:
Program Code: 2
class Main {
public static void main (String [] args ){
//&& Operator
System.out.println((5>3)&&8>5));// true
System.out.println((5>3)&&(8<5));//false
// || Operator
System.out.println((5<3) ||(8>5));// true
System.out.println((5<3) ||(8<5));// true
System.out.println((5<3) ||(8<5));// false
// ! Operator
System.out.println(!5==3));//true
System.out.println(!5>3));//false
}
}
Output:
Program Code: 3
class check EvenOdd
{
public static void main (String args [])
{
int num = 10;
System.out.println(“Enter an Integer number:”);
/* IF number is divisible by 2 then it’s an even number*else odd number*/
If (num%2==0)
System.out.println(“Entered number is even”);
else
System.out.println(“Entered number is odd”);
}
}
Output:.
Practical : 4
Switch-Case Statement
Program Code: 1
Public class SwitchCaseExample1 {
Public static void main(String args[]){
Int num=2;
Switch(num+2)
{
Case 1:
System.out.println(“Case1: Value is: “+num);
Case 2:
System.out.println(“Case2: Value is: “+num);
Case 3:
System.out.println(“Case3: Value is: “+num);
Default:
System.out.println(“Default: Value is: “+num); }
}
}
Output:
Program Code: 2
import java.util.scanner;
class main {
public static void main (String [] args){
// take input from users
Scanner input= new Scanner ( System.in);
System.out.println(“Enter your marks:”);
double marks = input.next Double ();
// ternary operator checks if
// marks is greater than 40
String result = (marks>40)?”pass”:”fail”;
System.out.println(“You”+ result+”the exam:”);
input.close();
}
}
Output:
Program Code: 3
//Java program to check the size
// Using switch…case statement.
class Main {
public static void main (String [] args){
int number = 44;
String size ;
// Switch statement to check size
Switch (number){
Case 29:
Size =”samll”;
break;
Case 42:
Size = “ medium”;
break;
// Match the value of week
Case 44 :
Size=”Large”;
break;
Case 48:
Size = “ Extra large”;
break;
default:
Size= “ unknown”;
break;
}
System.out.println(“size:”+size);
}
}
Output:
Practical : 5
For Loop Statement
Program Code: 1
class main {
public static void main (String [] args){
System.out.println(“command-line arguments are”);
//Loop through all arguments for (String str: args){
System.out.println (str);
}
}
}
Output:
Program Code: 2
//Program to print a text 5 times
class main {
public static void main (String [] args){
int n=5;
// for Loop
For (int I = 1; i<=n;++I){
System.out.println(“Techbajao”);
}
}
}
Output:
Program Code: 3
public class main {
public static void main (String [] args){
int rows =5,k=0;
for (int I=1; I<=rows;++I,k=0){
for (int space=1; space<=rows-I;++ space){
System.out.print(“”);
}
While(k!=2*i-1){
System.out.print(“*”);
++K;
}
System.out.println();
}
}
}
Output:
Practical: 6
While, Do- While Statement
Program Code: 1
Public class DoWhileExample {
Public static void main(String[] args) {
Int i=1;
Do{
System.out.println(i);
I++;
}while(i<=10);
}
}
Output:
Program Code : 2
class MyLoop
{
public static void main (String args [])
{
int I=1;
do
{
System.out.println(i);
I++;
}
While(I<=50);
}
}
Output:
Practical: 7 And 8
Implementation of implicit type casting.
Program Code: 1
Public class ImplicitTypecastingExample {
Public static void main(String args[]) {
Byte p = 12;
System.out.println(“byte value : “+p);
// Implicit Typecasting
Short q = p;
System.out.println(“short value : “+q);
Int r = q;
System.out.println(“int value : “+r);
Long s = r;
System.out.println(“long value : “+s);
Float t = s;
System.out.println(“float value : “+t);
Double u = t;
System.out.println(“double value : “+u); }
}
Output:
Program Code: 2
// Java Program to Illustrate Automatic Type Conversion
// Main class
Class GFG {
// Main driver method
Public static void main(String[] args)
{
Int I = 100;
// Automatic type conversion
// Integer to long type
Long l = I;
// Automatic type conversion
// Automatic type conversion
// long to float type
Float f = l;
// Print and display commands
System.out.println(“Int value “ + i);
System.out.println(“Long value “ + l);
System.out.println(“Float value “ + f);
}
}
Output:
Practical: 9
Implementation of explicit type conversion.
Program Code: 1
// Java program to Illustrate Explicit Type Conversion
// Main class
Public class GFG {
// Main driver method
Public static void main(String[] args)
{
// Double datatype
Double d = 100.04;
// Explicit type casting by forcefully getting
// data from long datatype to integer type
Long l = (long)d;
// Explicit type casting
Int I = (int)l;
// Print statements
System.out.println(“Double value “ + d);
// While printing we will see that
// fractional part lost
System.out.println(“Long value “ + l);
// While printing we will see that
// fractional part lost
System.out.println(“Int value “ + i);
}
}
Output:

Program Code: 2
// Java Program to Illustrate Conversion of
// Integer and Double to Byte
// Main class
Class GFG {
// Main driver method
Public static void main(String args[])
{
// Declaring byte variable
Byte b;
// Declaring and initializing integer and double
Int I = 257;
Double d = 323.142;
// Display message
System.out.println(“Conversion of int to byte.”);
// I % 256
B = (byte)I;
// Print commands
System.out.println(“I = “ + I + “ b = “ + b);
System.out.println(
“\nConversion of double to byte.”);
// d % 256
B = (byte)d;
// Print commands
System.out.println(“d = “ + d + “ b= “ + b);
}
}
Output:
Practical: 10
Implementation of constructor and multiple constructors.
Program Code: 1
//Java Program to create and call a default constructor
Class Bike1{
//creating a default constructor
Bike1(){System.out.println(“Bike is created”);}
//main method
Public static void main(String args[]){
//calling a default constructor
Bike1 b=new Bike1();
}
}
Output:
Program Code: 2
//Java Program to demonstrate the use of the parameterized constructor.
Class Student4{
Int id;
String name;
//creating a parameterized constructor
Student4(int I,String n){
Id = I;
Name = n;
}
//method to display the values
Void display(){System.out.println(id+” “+name);}
Public static void main(String args[]){
//creating objects and passing values
Student4 s1 = new Student4(111,”Karan”);
Student4 s2 = new Student4(222,”Aryan”);
//calling method to display the values of object
S1.display();
S2.display();
}
}
Output:
Program Code: 3
Public class ComplexNumber{
//for real and imaginary parts of complex numbers
Double real, img;
//constructor to initialize the complex number
ComplexNumber(double r, double i){
This.real = r;
This.img = I;
}
Public static ComplexNumber sum(ComplexNumber c1, ComplexNumber c2)
{
//creating a temporary complex number to hold the sum of two numbers
ComplexNumber temp = new ComplexNumber(0, 0);
Temp.real = c1.real + c2.real;
Temp.img = c1.img + c2.img;
//returning the output complex number
Return temp;
}
Public static void main(String args[]) {
ComplexNumber c1 = new ComplexNumber(5.5, 4);
ComplexNumber c2 = new ComplexNumber(1.2, 3.5);
ComplexNumber temp = sum(c1, c2);
System.out.printf(“Sum is: “+ temp.real+” + “+ temp.img +”I”);
}
}
Output:
Practical: 11 And 12
Implementation of different functions of String Class.
Program Code: 1
Public class StringMethodsDemo {
Public static void main(String[] args) {
String targetString = “Java is fun to learn”;
String s1= “JAVA”;
String s2= “Java”;
String s3 = “ Hello Java “;
System.out.println(“Char at index 2(third position): “ + targetString.charAt(2));
System.out.println(“After Concat: “+ targetString.concat(“-Enjoy-“));
System.out.println(“Checking equals ignoring case: “ +s2.equalsIgnoreCase(s1));
System.out.println(“Checking equals with case: “ +s2.equals(s1));
System.out.println(“Checking Length: “+ targetString.length());
System.out.println(“Replace function: “+ targetString.replace(“fun”, “easy”));
System.out.println(“SubString of targetString: “+ targetString.substring(8));
System.out.println(“SubString of targetString: “+ targetString.substring(8, 12));
System.out.println(“Converting to lower case: “+ targetString.toLowerCase());
System.out.println(“Converting to upper case: “+ targetString.toUpperCase());
System.out.println(“Triming string: “ + s3.trim());
System.out.println(“searching s1 in targetString: “ + targetString.contains(s1));
System.out.println(“searching s2 in targetString: “ + targetString.contains(s2));
Char [] charArray = s2.toCharArray();
System.out.println(“Size of char array: “ + charArray.length);
System.out.println(“Printing last element of array: “ + charArray[3]);
}
}
Output:
Program Code: 2
Class Str
{
Public static void main( String args[] )
{
StringBuffer s = new StringBuffer(“Coding Atharva”);
System.out.println(“\n String = “+s); // Will Print the string
System.out.println(“\n Length = “+s.length() ); // total numbers of characters
System.out.println(“\n Length = “+s.capacity() ); // total allocated capacity
s.setLength(6); // Sets the length and destroy the remaining characters
System.out.println(“\n After setting length String = “+s );
s.setCharAt(0,’K’); // It will change character at specified position
System.out.println(“\n SetCharAt String = “+s );
s.setCharAt(0,’C’);
int a = 007;
s.append(a); // It concatenates the other data type value
System.out.println(“\n Appended String = “+s );
s.insert(6,” Atharva”); // used to insert one string or char or object
System.out.println(“\n Inserted String = “+s );
s.reverse();
System.out.println(“\n Reverse String = “+s );
s.reverse();
s.delete(6,14); // used to delete sequence of character
System.out.println(“\n\n After deleting string=”+s);
}
}
Output:
Practical: 13
Implementation of Arrays in Java.
Program Code: 1
//Java Program to illustrate the use of multidimensional array
Class Testarray3{
Public static void main(String args[]){
//declaring and initializing 2D array
Int arr[][]={{1,2,3},{2,4,5},{4,4,5}};
//printing 2D array
For(int i=0;i<3;i++){
For(int j=0;j<3;j++){
System.out.print(arr[i][j]+” “);
}
System.out.println(); }
}
}
Output:
Program Code: 2
//Java Program to print the array elements using for-each loop
Class Testarray1{
Public static void main(String args[]){
Int arr[]={33,3,4,5};
//printing array using for-each loop
For(int i:arr)
System.out.println(i);
}
}
Output:
Practical: 14
Implementation of Vectors in Java.
Program Code: 1
Import java.util.*;
Public class VectorInsertElementAtExample1 {
Public static void main(String arg[]) {
//Create an empty vector
Vector<Integer> vec = new Vector<>();
//Add element in the vector
Vec.add(10);
Vec.add(20);
Vec.add(30);
Vec.add(40);
Vec.add(50);
//Printing the element
System.out.println(“Element in vector before insertion = “+vec);
//Insert the element at 2nd position
Vec.insertElementAt(700, 2);
System.out.println(“Element in vector after insertion = “+vec); }
}
Output:
Program Code: 2
Import java.util.*;
Public class VectorExample2 {
Public static void main(String args[]) {
//Create an empty Vector
Vector<Integer> in = new Vector<>();
//Add elements in the vector
In.add(100);
In.add(200);
In.add(300);
In.add(200);
In.add(400);
In.add(500);
In.add(600);
In.add(700);
//Display the vector elements
System.out.println(“Values in vector: “ +in);
//use remove() method to delete the first occurrence of an element
System.out.println(“Remove first occourence of element 200: “+in.remove((Integer)200));
//Display the vector elements afre remove() method
System.out.println(“Values in vector: “ +in);
//Remove the element at index 4
System.out.println(“Remove element at index 4: “ +in.remove(4));
System.out.println(“New Value list in vector: “ +in);
//Remove an element
In.removeElementAt(5);
//Checking vector and displays the element
System.out.println(“Vector element after removal: “ +in);
//Get the hashcode for this vector
System.out.println(“Hash code of this vector = “+in.hashCode());
//Get the element at specified index
System.out.println(“Element at index 1 is = “+in.get(1));
}
}
Output:
Practical: 15 And 16.
Implementation of Wrapper Class to convert primitive into object and object into primitive.
Program Code: 1
// Java program to illustrate
// various Integer methods
Public class Integer_test {
Public static void main(String args[])
{
Int b = 55;
String bb = “45”;
// Construct two Integer objects
Integer x = new Integer(b);
Integer y = new Integer(bb);
// toString()
System.out.println(“toString(b) = “
+ Integer.toString(b));
// toHexString(),toOctalString(),toBinaryString()
// converts into hexadecimal, octal and binary
// forms.
System.out.println(“toHexString(b) =”
+ Integer.toHexString(b));
System.out.println(“toOctalString(b) =”
+ Integer.toOctalString(b));
System.out.println(“toBinaryString(b) =”
+ Integer.toBinaryString(b));
// valueOf(): return Integer object
// an overloaded method takes radix as well.
Integer z = Integer.valueOf(b);
System.out.println(“valueOf(b) = “ + z);
Z = Integer.valueOf(bb);
System.out.println(“ValueOf(bb) = “ + z);
Z = Integer.valueOf(bb, 6);
System.out.println(“ValueOf(bb,6) = “ + z);wel
// parseInt(): return primitive int value
// an overloaded method takes radix as well
Int zz = Integer.parseInt(bb);
System.out.println(“parseInt(bb) = “ + zz);
Zz = Integer.parseInt(bb, 6);
System.out.println(“parseInt(bb,6) = “ + zz);
// getInteger(): can be used to retrieve
// int value of system property
Int prop
= Integer.getInteger(“sun.arch.data.model”);
System.out.println(
“getInteger(sun.arch.data.model) = “ + prop);
System.out.println(“getInteger(abcd) =”
+ Integer.getInteger(“abcd”));
// an overloaded getInteger() method
// which return default value if property not found.
System.out.println(
“getInteger(abcd,10) =”
+ Integer.getInteger(“abcd”, 10));
// decode() : decodes the hex,octal and decimal
// string to corresponding int values.
String decimal = “45”;
String octal = “005”;
String hex = “0x0f”value
Integer dec = Integer.decode(decimal);
System.out.println(“decode(45) = “ + dec);
Dec = Integer.decode(octal);
System.out.println(“decode(005) = “ + dec);
Dec = Integer.decode(hex);
System.out.println(“decode(0x0f) = “ + dec);
// rotateLeft and rotateRight can be used
// to rotate bits by specified distance
Int valrot = 2;
System.out.println(
“rotateLeft(0000 0000 0000 0010 , 2) =”
+ Integer.rotateLeft(valrot, 2));
System.out.println(
“rotateRight(0000 0000 0000 0010,3) =”
+ Integer.rotateRight(valrot, 3));
}
}
Output:
Program Code: 2
Public class MyStringToInteger {
Public static void main(String a[]){
String str = “23”;
Integer I = Integer.valueOf(str);
System.out.println(“The integer value: “+i);
}
}
Output:
Program Code: 3
Public class CharacterClassExample {
Public static void main(String[] args) {
Char ch1, ch2;
Ch1 = ‘9’;
Ch2 = ‘V’;
Boolean b1, b2;
B1 = Character.isDigit(ch1);
B2 = Character.isDigit(ch2);
String str1 = ch1 + “ is a digit is “ + b1;
String str2 = ch2 + “ is a digit is “ + b2;
System.out.println( str1 );
System.out.println( str2 );
}
}
Output:
Program Code: 4
Public class IntegerToNumericPrimitiveTypesExample {
Public static void main(String[] args) {
Integer intObj = new Integer(“10”);
//use byteValue method of Integer class to convert it into byte type.
Byte b = intObj.byteValue();
System.out.println(b);
//use shortValue method of Integer class to convert it into short type.
Short s = intObj.shortValue();
System.out.println(s);
//use intValue method of Integer class to convert it into int type.
Int I = intObj.intValue();
System.out.println(i);
//use floatValue method of Integer class to convert it into float type.
Float f = intObj.floatValue();
System.out.println(f);
//use doubleValue method of Integer class to convert it into double type.
Double d = intObj.doubleValue();
System.out.println(d);
}
}
Output:
Practical: 17
Implementation the concept of overriding.
Program Code: 1
//Java Program to illustrate the use of Java Method Overriding
//Creating a parent class.
Class Vehicle{
//defining a method
Void run(){System.out.println(“Vehicle is running”);}
}
//Creating a child class
Class Bike2 extends Vehicle{
//defining the same method as in the parent class
Void run(){System.out.println(“Bike is running safely”);}

Public static void main(String args[]){


Bike2 obj = new Bike2();//creating object
Obj.run();//calling method
}
}
Output:
Program Code: 2
Class Bank{
Int getRateOfInterest(){return 0;}
}
//Creating child classes.
Class SBI extends Bank{
Int getRateOfInterest(){return 8;}
}
Class ICICI extends Bank{
Int getRateOfInterest(){return 7;}
}
Class AXIS extends Bank{
Int getRateOfInterest(){return 9;}
}
//Test class to create objects and call the methods
Class Test2{
Public static void main(String args[]){
SBI s=new SBI();
ICICI i=new ICICI();
AXIS a=new AXIS();
System.out.println(“SBI Rate of Interest: “+s.getRateOfInterest());
System.out.println(“ICICI Rate of Interest: “+i.getRateOfInterest());
System.out.println(“AXIS Rate of Interest: “+a.getRateOfInterest());
}
}
Output:

Program Code: 3
Class Animal
{
Animal getObj()
{
System.out.println(“Animal object”);
Return new Animal();
}
}
Class Dog extends Animal
{
Dog getObj() //Legal override after Java5 onward
{ System.out.println(“Dog object”);
Return new Dog();
}
Public static void main(String[] args) {
New Dog().getObj();
}
}
Output:
Practical: 18
Implementation of single and Multilevel inheritance.
Program Code: 1
// Java program to illustrate the
// concept of single inheritance
Import java.io.*;
Import java.lang.*;
Import java.util.*;
Class one {
Public void print_geek()
{
System.out.println(“Geeks”);
}
}
Class two extends one {
Public void print_for() { System.out.println(“for”); }
}
// Driver class
Public class Main {
Public static void main(String[] args)
{
Two g = new two();
g.print_geek();
g.print_for();
g.print_geek();
}
}
Output:

Program Code: 2
// Java program to illustrate the
// concept of Multilevel inheritance
Import java.io.*;
Import java.lang.*;
Import java.util.*;
Class one {
Public void print_geek()
{
System.out.println(“Geeks”);
}
}
Class two extends one {
Public void print_for() {
System.out.println(“for”);
}
}
Class three extends two {
Public void print_geek()
{
System.out.println(“Geeks”);
}
}
// Drived class
Public class Main {
Public static void main(String[] args)
{
Three g = new three();
g.print_geek();
g.print_for();
g.print_geek();
}
}
Output:
Program Code: 3
Class Car{
Public Car()
{
System.out.println(“Class Car”);
}
Public void vehicleType()
{
System.out.println(“Vehicle Type: Car”);
}
}
Class Maruti extends Car{
Public Maruti()
{
System.out.println(“Class Maruti”);
}
Public void brand()
{
System.out.println(“Brand: Maruti”);
}
Public void speed()
{
System.out.println(“Max: 90Kmph”);
}
}
Public class Maruti800 extends Maruti{

Public Maruti800()
{
System.out.println(“Maruti Model: 800”);
}
Public void speed()
{
System.out.println(“Max: 80Kmph”);
}
Public static void main(String args[])
{
Maruti800 obj=new Maruti800();
Obj.vehicleType();
Obj.brand();
Obj.speed();
}
}
Output:
Program Code: 4
Class Room
{
Int length,width;
Room(int a,int b)
{
Length = a;
Width = b;
}
Void area()
{
Int area = length*width;
System.out.println(“The area of the room is “ +area);
}
}
Class roomvol extends Room
{
Int height;
Roomvol(int a,int b,int c)
{
Super(a,b);
Height = c;
}
Void volume()
{
Int volume = length*width*height;
System.out.println(“The volume of the room is “ +volume);
}
}
Class inheritance3
{
Public static void main(String args[])
{
Roomvol room2 = new roomvol(10,40,20);
Room2.area();
Room2.volume();
}
}
Output:

You might also like