0% found this document useful (0 votes)
8 views7 pages

Java Programming Concepts and Examples

The document contains several Java programming examples demonstrating key concepts such as classes, inheritance, interfaces, packages, exceptions, and multithreading. Each example includes code snippets along with their expected outputs, illustrating how to perform operations like addition, calculate student marks, implement shapes, handle exceptions, and manage threads. The examples serve as practical demonstrations for understanding Java programming fundamentals.

Uploaded by

lovelykavin598
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)
8 views7 pages

Java Programming Concepts and Examples

The document contains several Java programming examples demonstrating key concepts such as classes, inheritance, interfaces, packages, exceptions, and multithreading. Each example includes code snippets along with their expected outputs, illustrating how to perform operations like addition, calculate student marks, implement shapes, handle exceptions, and manage threads. The examples serve as practical demonstrations for understanding Java programming fundamentals.

Uploaded by

lovelykavin598
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

EX:NO=1 Objects And Class

import [Link].*;
class addition
{
int a,b,sum=0;
public void add()
{
a=5;
b=3;
sum=a+b;
[Link]("value of sum:"+sum);
}
}
class textadd
{
public static void main(String args[])
{
addition a=new addition();
[Link]();
}
}

OUTPUT: value of sum: 8

[Link] Inheritance
import [Link].*;
class student
{
int regno;
String name;
int age;
public void details()
{
regno=12345;
name="abi";
age=20;
}
}
class mark extends student
{
int m1,m2,m3,total;
float avg;
public void calculate()
{
m1=71;
m2=83;
m3=64;
total=m1+m2+m3;
avg=total/3;
}
public void display()
{
[Link]("Name:"+name);
[Link]("Regno:"+regno);
[Link]("Age:"+age);
[Link]("Total:"+total);
[Link]("Average:"+avg);
}
}
class inherit
{
public static void main(String arge[])
{
mark mk=new mark();
[Link]();
[Link]();
[Link]();
}
}

OUTPUT:
Name : Abi
Rego :12345
Age: 20
Total: 218
Average:72.67

[Link] Interface
import [Link].*;
interface shape
{
void area();
}
class rect implements shape
{
int l,b,A;
public void area()
{
l=5;
b=3;
A=l*b;
[Link]("Area of Rectngle"+A);
}
}
class square implements shape
{
int r,A;
public void area()
{
r=3;
A=r*r;
[Link]("Area of square"+A);
}
}
class intershape
{
public static void main(String args[])
{
rect R=new rect();
square S=new square();
[Link]();
[Link]();
}
}

OUTPUT:
Area of Rectngle : 15
Area of square : 9

[Link] Package

package arith;
public class arithpac
{
public void add()
{
int a,b;
a=5;
b=6;
[Link]("addition:"+(a+b));
}
public void sub()
{
int a,b;
a=15;
b=6;
[Link]("subraction:"+(a-b));
}
}

import arith.*;
import [Link].*;
class packtxt
{
public static void main(String args[])
{
arithpac ag=new arithpac();
[Link]();
[Link]();
}
}
OUTPUT:
bin> javac arith/[Link]
bin>javac [Link]
bin>java packtest
Addition : 11
Subtraction : 9

[Link].1 Build in Exception


import [Link].*;
import [Link];
class exception3
{
public static void main(String args[])
{
try
{
try
{
int[]arr={1,2,3};
int a=arr[1]+arr[3];
}
catch(ArrayIndexOutOfBoundsException e2)
{
[Link]("Array Index Out of Bounds Exception");
}
try
{
int b=5/0;
}
catch(ArithmeticException e1)
{
[Link]("Divided by zero exception");
}
int i[]=null;
int j=i[1];
}
catch(NullPointerException e3)
{
[Link]("null pointer exception");
}
finally
{
[Link]("program Ends with finally block");
}
}
}
OUTPUT:
Array Index out of Bounds Exception
Divided by zero Exception
Null pointer Exception
Program Ends with finally block

[Link].2 User defined Exception


import [Link].*;
import [Link];
class AgeException extends Exception
{
public AgeException()
{
[Link]("Age is not Valid to vote");
}
}
class userexcep
{
public static void main(String arg[])throws AgeException
{
try
{
int age=17;
if(age<18)
{ throw new AgeException(); }
else
{ [Link]("valid to vote");}
}
catch(AgeException ae)
{
[Link]("Age is under 18:"+ae);
}
[Link]("Validation Completed");
}
}

OUTPUT:
Age is not valid to vote
Age is under 18: Age Exception
Validation Completed

[Link] Multithreading
import [Link].*;
class thread1 extends Thread
{
public void run()
{
for (int i=1;i<5;i++)
{
[Link]("I am T1");
}
}
}
class thread2 implements Runnable
{
public void run()
{
for (int i=1;i<5;i++)
{
[Link]("I am T2");
}
}
}
class threadtest
{
public static void main(String arg[])
{
thread1 t1=new thread1();
[Link]();
thread2 ru=new thread2();
Thread t2=new Thread (ru);
[Link]();
try
{
[Link]("Suspend Thread1");
[Link]();
[Link](100);
[Link]("Resume Thread1");
[Link]();
}
catch(InterruptedException e)
{}
}
}
OUTPUT:
Suspend Thread1
I am T2
I am T2
I am T2
I am T2
Resume Thread1
I am T1
I am T1
I am T1
I am T1

Common questions

Powered by AI

The use of inheritance, letting 'mark' class extend 'student', is effective for reusing attributes and their initialization. However, improvements could involve creating an interface for student details, aiding polymorphism and more flexible extension e.g., different student types. Moreover, encapsulation levels can be adjusted to prevent unauthorized access and modifications, favoring private access to variables with public getter/setter functions where appropriate .

The multithreading concept is demonstrated through classes 'thread1' extending 'Thread' and 'thread2' implementing 'Runnable'. Each runs separate tasks, 'I am T1' and 'I am T2' respectively. Multithreading allows both tasks to execute concurrently, improving application performance by utilizing CPU resources efficiently. The code further illustrates controlling threads' execution using 'suspend' and 'resume'. These exemplify synchronization and the ability to pause and resume threads, although contemporary Java discourages using 'suspend' and 'resume' due to potential deadlocks .

Packages in Java, such as 'arith', facilitate code organization by grouping related classes together, enhancing maintainability and readability. In 'arithpac', logical grouping avoids name conflicts and provides controlled access to classes. It allows structured and scalable application development and reusability by importing necessary classes only rather than cluttering the global namespace .

The Java programs effectively catch specific exceptions like 'ArrayIndexOutOfBoundsException' and 'ArithmeticException', which prevents the program from crashing. However, the reliance on broad exception types could be refined by handling specific conditions more granularly. The use of a 'finally' block ensures that resource cleanup occurs. Improvements could include more informative messages and differentiation between user-defined and built-in exceptions to aid debugging .

By implementing the 'shape' interface, the classes 'rect' and 'square' adhere to a common template without sharing code, allowing each class to define its own 'area' method. This enhances modularity, as changes to shape processing don't affect unrelated classes, promoting a separation of concerns. Additionally, it allows flexibility to add new shapes by merely implementing the 'shape' interface, abiding by the open-closed principle .

The 'finally' block guarantees execution of specific instructions after try-catch blocks, irrespective of an exception occurrence, as seen by the message 'program Ends with finally block'. Its significance lies in resource management, ensuring resources are released even if an error occurs, maintaining application stability and predictable behavior .

Thread suspension using 'suspend' and 'resume' presents risks like deadlocks, where threads cease to progress if suspended in an unprotected state. Best practices have evolved to discourage these methods, favoring alternatives like 'wait' and 'notify', or high-level constructs such as 'Lock' objects and 'ExecutorService', which provide safer thread state control and avoid concurrency issues, enhancing stability and reliability .

User-defined exceptions allow customization of response to specific conditions. The 'AgeException', for instance, is triggered with 'throw' when age is less than 18, printing a specific message. The 'catch' block handles this exception, maintaining the program's flow and enabling specific error management, indicating a meaningful domain-specific validation mechanism rather than using generic exceptions .

Error handling is crucial for managing exceptions and ensuring program robustness. It is implemented using 'try-catch' blocks to handle specific errors like 'ArrayIndexOutOfBoundsException', 'ArithmeticException', and 'NullPointerException'. For example, an 'ArrayIndexOutOfBoundsException' is caught when an invalid array index is accessed, while a 'finally' block ensures the program correctly finishes by printing 'program Ends with finally block' despite exceptions encountered .

The classes 'student' and 'mark' demonstrate inheritance by allowing 'mark' to extend 'student'. This means 'mark' inherits the properties of 'student', such as 'regno', 'name', and 'age', while also introducing new properties 'm1', 'm2', 'm3', 'total', and 'avg'. The method 'details' in 'student' sets values for the inherited attributes, which 'mark' can use to calculate and display student details, thus showing code reusability and hierarchical class structure .

You might also like