0% found this document useful (0 votes)
49 views23 pages

Prac 1 Java

The document contains descriptions of 9 programming practical exercises. Practical #7 asks the reader to write a program that takes a file as input at runtime, then counts and displays the number of lines, words, and characters in that file. It provides code to open the file, read it line by line using a BufferedReader, and initialize counters to track the number of words, characters, lines, paragraphs, sentences, and whitespace.

Uploaded by

Arushi Saklani
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)
49 views23 pages

Prac 1 Java

The document contains descriptions of 9 programming practical exercises. Practical #7 asks the reader to write a program that takes a file as input at runtime, then counts and displays the number of lines, words, and characters in that file. It provides code to open the file, read it line by line using a BufferedReader, and initialize counters to track the number of words, characters, lines, paragraphs, sentences, and whitespace.

Uploaded by

Arushi Saklani
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/ 23

PRACTICAL#1

OBJECT: Write a program to display the count of all commands line arguments and list
each in a line.
REQUREMENT: Java platform for program execution.
PROGRAM:
public class argu{

public static void main(String[] arguments) {

String wordToFind = "GFG.";

System.out.println("Arguments passed at runtime. " + "We can get that by using


args.length and it is " + arguments.length + " here ");

for(int i = 0; i < arguments.length; i++) {


if (arguments[i].equalsIgnoreCase(wordToFind)) {

System.out.println("Provided word "+ wordToFind + " is present " +


"and it is at location " + (i+1));
}
}
}
}
OUTPUT:

1
PRACTICAL#2
OBJECT: Write a program to find the sum of two given numbers.
REQUREMENT: Java platform for program execution.
PROGRAM:
import java.util.*;
class sum
{
public void main()
{
int num1,num2,Sum;
Scanner sc=new Scanner(System.in);
System.out.println("Enter the value of num1 is:");
num1=sc.nextInt();
System.out.println("Enter the value of num2 is:");
num2=sc.nextInt();
Sum=num1+num2;
System.out.println("The sum of two numbers is:"+Sum);
}
}
OUTPUT:

2
PRACTICAL#3
OBJECT: Write a program to print the multiplication table in row and column format.
REQUIREMENT: Java platform for program execution.
PROGRAM:
/* Prints multiplication table in Java */
public class table {

public static void main(String[] args) {


int tableSize = 9;
printMultiplicationTable(tableSize);
}

public static void printMultiplicationTable(int tableSize) {


// first print the top header row
System.out.format(" ");
for(int i = 1; i<=tableSize;i++ ) {
System.out.format("%4d",i);
}
System.out.println();
System.out.println("------------------------------------------");

for(int i = 1 ;i<=tableSize;i++) {
// print left most column first
System.out.format("%4d |",i);
for(int j=1;j<=tableSize;j++) {
System.out.format("%4d",i*j);
}
System.out.println();
}
}
}
OUTPUT:

3
PRACTICAL#4
OBJECT: Write a program to
a) To find whether the given number is prime or not
b) To display all prime numbers in a given range of numbers
REQUIREMENT: Java platform for program execution.
PROGRAM:
a)public class prime{
public static void main(String args[]){
int i,m=0,flag=0;
int n=3;//it is the number to be checked
m=n/2;
if(n==0||n==1){
System.out.println(n+" is not prime number");
}else{
for(i=2;i<=m;i++){
if(n%i==0){
System.out.println(n+" is not prime number");
flag=1;
break;
}
}
if(flag==0) { System.out.println(n+" is prime number"); }
}//end of else
}
}
OUTPUT:

4
b) import java.util.Scanner;
class table2
{
public static void main(String arg[])
{
int i,count;
System.out.print("Enter n value : ");
Scanner sc=new Scanner(System.in);
int n=sc.nextInt();
System.out.println("Prime numbers between 1 to "+n+" are ");
for(int j=2;j<=n;j++)
{
count=0;
for(i=1;i<=j;i++)
{
if(j%i==0)
{
count++;
}
}
if(count==2)
System.out.print(j+" ");
}
}
}
OUTPUT:

5
PRACTICAL#5
OBJECT: Write a program to create an array of integers and accept a number. Check
whether it exits in the array. Create your own exception with appropriate error message and
raise the exception when the element is not found in the array.
REQUIREMENT: Java platform for program execution.
PROGRAM:
class array1 {
public static void main(String[] args) {

int[] num = {1, 2, 3, 4, 5};


int toFind = 3;
boolean found = false;

for (int n : num) {


if (n == toFind) {
found = true;
break;
}
}

if(found)
System.out.println(toFind + " is found.");
else
System.out.println(toFind + " is not found.");
}
}
OUTPUT:

6
PRACTICAL#6
OBJECT: Write a program to copy a file to another file using java.io package Classes.
REQUIREMENT: Java platform for program execution.
PROGRAM:
import java.io.*;

public class copyfile {


public static void main(String[] args) throws Exception {
BufferedWriter out1 = new BufferedWriter(new FileWriter("srcfile"));
out1.write("string to be copied\n");
out1.close();
InputStream in = new FileInputStream(new File("srcfile"));
OutputStream out = new FileOutputStream(new File("destnfile"));
byte[] buf = new byte[1024];
int len;

while ((len = in.read(buf)) > 0) {


out.write(buf, 0, len);
}
in.close();
out.close();
BufferedReader in1 = new BufferedReader(new FileReader("destnfile"));
String str;

while ((str = in1.readLine()) != null) {


System.out.println(str);
}
in.close();
}
}
OUTPUT:

7
PRACTICAL#8
OBJECT: Programming exercise on Arrays and String
REQUIREMENT: Java platform for program execution.
PROGRAM:
a) Write a Java program to sort a numeric array and a string array.

import java.util.Arrays;
public class array1 {
public static void main(String[] args){

int[] my_array1 = {
1789, 2035, 1899, 1456, 2013,
1458, 2458, 1254, 1472, 2365,
1456, 2165, 1457, 2456};

String[] my_array2 = {
"Java",

"Python",
"PHP",
"C#",
"C Programming",
"C++"
};
System.out.println("Original numeric array : "+Arrays.toString(my_array1));
Arrays.sort(my_array1);
System.out.println("Sorted numeric array : "+Arrays.toString(my_array1));

System.out.println("Original string array : "+Arrays.toString(my_array2));


Arrays.sort(my_array2);
System.out.println("Sorted string array : "+Arrays.toString(my_array2));
}
}
OUTPUT:

8
(b) Write a Java program to find the second largest element in an array.

import java.util.Arrays;
public class array2 {
public static void main(String[] args) {
int[] my_array = {
10789, 2035, 1899, 1456, 2013,
1458, 2458, 1254, 1472, 2365,
1456, 2165, 1457, 2456};
System.out.println("Original numeric array : "+Arrays.toString(my_array));
Arrays.sort(my_array);
int index = my_array.length-1;
while(my_array[index]==my_array[my_array.length-1]){
index--;
}
System.out.println("Second largest value: " + my_array[index]);
}
}
OUTPUT:

9
PRACTICAL#9
OBJECT: Programming exercise on inheritance
REQUIREMENT: Java platform for program execution.
PROGRAM:
class Inheritance
{
public static void main(String args[]){
System.out.println(&quot;EXAMPLE OF SINGLE INHERITANCE -------------------
&quot;);
son obj =new son();
obj.getdata(10, 20);
obj.disp();
}
}
class father{
int a,b;
void getdata(int x,int y){
a=x;
b=y;
}
}
class son extends father{
int add(){
int sum=a+b;
return sum;
}
void disp(){
System.out.println(&quot; Sum of the number=-------------------&quot;+add());
}

10
}
OUTPUT:

11
PRACTICAL#7

OBJECT: Write a program to get a file at runtime and display the number of lines, words
and characters in that file.
REQUIREMENT: Java platform for program execution.
PROGRAM:
// Java program to count the
// number of lines, words, sentences,  
// characters, and whitespaces in a file
import java.io.*;
  
public class Test {
    public static void main(String[] args)
        throws IOException
    {
        File file = new File("C:\\Users\\hp\\Desktop\\TextReader.txt");
        FileInputStream fileInputStream = new FileInputStream(file);
        InputStreamReader inputStreamReader = new InputStreamReader(fileInputStream);
        BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
  
        String line;
        int wordCount = 0;
        int characterCount = 0;
        int paraCount = 0;
        int whiteSpaceCount = 0;
        int sentenceCount = 0;
  
        while ((line = bufferedReader.readLine()) != null) {
            if (line.equals("")) {
                paraCount += 1;
            }
            else {
                characterCount += line.length();
                String words[] = line.split("\\s+");
                wordCount += words.length;
                whiteSpaceCount += wordCount - 1;
                String sentence[] = line.split("[!?.:]+");
                sentenceCount += sentence.length;
            }
        }
        if (sentenceCount >= 1) {
            paraCount++;
        }
        System.out.println("Total word count = "+ wordCount);
        System.out.println("Total number of sentences = "+ sentenceCount);
        System.out.println("Total number of characters = "+ characterCount);
        System.out.println("Number of paragraphs = "+ paraCount);
12
        System.out.println("Total number of whitespaces = "+ whiteSpaceCount);
    }
}

Output:

13
PRACTICAL#10
OBJECT: Write program for exception handling
REQUIREMENT: Java platform for program execution.
PROGRAM:
package excep;
public class Excep {
public static void main(String[] args) {
// default throw our catch
//for integer values

try{
int data=100/0;
}
catch(ArithmeticException e){
System.out.println(e);
}
System.out.println("rest of the code....");

//for null values

String a=null;
try{
System.out.print(a.length());
}
catch(NullPointerException e){
System.out.println(e.getMessage());
}

our throw default catch


14
int i=10;
int b=15;

try{
if(i<b)
{
throw new ArithmeticException("OMG.....Balance is very low");

}
}
finally{
System.out.println("Program terminated safely");
}

String a1=null;
try{
if(a1==null){
throw new NullPointerException("Null Value");
}
}
catch(NullPointerException e){
System.out.println(e.getMessage());
}
}
}
Output:

15
16
PRACTICAL#11
OBJECT: Write programs for multithreading
REQUIREMENT: Java platform for program execution.
PROGRAM:
package multithreading1;

class T1 implements Runnable{


public void run(){
int i,n=5,f=1,sum=0;
for(i=1;i<=n;i++){
f=f*i;
sum=sum+f;
}
System.out.println("Factorial is: "+sum);
}

;}

class T2 implements Runnable{


public void run(){
int i,j,sum=0;
int n=3;
for(i=1;i<=n;i++){
for(j=1;j<=i;j++){

sum+=j;
}

17
System.out.println("Sum of series: "+sum);
}
}
}

public class Multithreading1 {

public static void main(String[] args) {


Thread ta=new Thread(new T1());
Thread tb=new Thread(new T2());
ta.start();
tb.start();
}

}
Output:

18
PRACTICAL#12
OBJECT: Programming exercise on Java applets
REQUIREMENT: Java platform for program execution.
PROGRAM:
import java.applet.Applet;
import java.awt.*;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class app121 extends Applet {
Label l1,l2;
TextField t1,t2,t3;
Button b1,b2;

public void init() {


l1=new Label("First number");
l2=new Label("Second number");

t1=new TextField();
t2=new TextField();
t3=new TextField();
b1=new Button("Add");
b2=new Button("Clear");
setLayout(null);
l1.setBounds(30,50,100,20);
l2.setBounds(30,100,100,20);
t1.setBounds(150,50,100,20);

19
t2.setBounds(150,100,100,20);
t3.setBounds(150,150,100,20);
b1.setBounds(50,150,80,20);
b2.setBounds(100,200,80,20);
add(t1);
add(l1);
add(l2);
add(t2);
add(b1);
add(t3);
add(b2);
b1.addActionListener(new MyHandler());
}
public class MyHandler implements ActionListener{
public void actionPerformed(ActionEvent e){
int a,b,s;
a=Integer.parseInt(t1.getText());
b=Integer.parseInt(t2.getText());
s=a+b;
t3.setText("Sum is "+s);
}
}
public class My implements ActionListener{
public void actionPerformed(ActionEvent e){
t1.setText("");
t2.setText("");
t3.setText("");
20
}

}
}
Output:

21
PRACTICAL#13
OBJECT: Write program for Java Data base connectivity
REQUIREMENT: Java platform for program execution.
PROGRAM:
package insertion;
import java.sql.*;
import java.util.Scanner;

public class Insertion {

public static void main(String[] args) {


Scanner sc=new Scanner(System.in);

try{
int roll;
roll=sc.nextInt();
Class.forName("com.mysql.cj.jdbc.Driver");
Connection
con=DriverManager.getConnection("jdbc:mysql://localhost:3306/polystud","root
","Arushi0204@");

Statement st=con.createStatement();
String query="insert into cse3 values(101,'apple','csem09','working')";
st.executeUpdate(query);
System.out.println("One row inserted");

ResultSet rs=st.executeQuery("select *from cse3");


22
while(rs.next()){
System.out.println(rs.getInt(1)+" "+rs.getString(2)+" "+rs.getString(3)+"
"+rs.getString(4));

}
}
catch(Exception e){
System.out.println("Executed Successfully!!!!");
}
}

Output:

23

You might also like