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

AJP Unit I

The document discusses Java input/output streams and byte code. It describes common Java streams like System.in and System.out. It provides examples of using print, println and printf methods. It also discusses intermediate stream operations like filter and stream pipelining. Finally, it covers what byte code is in Java and its advantages like portability and performance optimization.

Uploaded by

srnarayanan_slm
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)
51 views

AJP Unit I

The document discusses Java input/output streams and byte code. It describes common Java streams like System.in and System.out. It provides examples of using print, println and printf methods. It also discusses intermediate stream operations like filter and stream pipelining. Finally, it covers what byte code is in Java and its advantages like portability and performance optimization.

Uploaded by

srnarayanan_slm
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/ 14

UNIT I

JAVA FUNDAMENTALS

1.1 Java IO : Input-output Streaming in Java with Examples

Java brings various Streams with its I/O package that helps the user to perform all the input-
output operations. These streams support all the types of objects, data-types, characters, files
etc to fully execute the I/O operations.

Before exploring various input and output streams lets look at 3 standard or default
streams that Java has to provide which are also most common in use:

1. System.in: This is the standard input stream that is used to read characters from the
keyboard or any other standard input device.
2. System.out: This is the standard output stream that is used to produce the result of a
program on an output device like the computer screen.
Here is a list of the various print functions that we use to output statements:
 print(): This method in Java is used to display a text on the console. This text is passed
as the parameter to this method in the form of String. This method prints the text on
the console and the cursor remains at the end of the text at the console. The next
printing takes place from just here.

 Syntax:
System.out.print(parameter);
Example:
// Java code to illustrate print()
import java.io.*;

class Demo_print {
public static void main(String[] args)
{

// using print()
// all are printed in the
// same line
System.out.print("GfG! ");
System.out.print("GfG! ");
System.out.print("GfG! ");
}
}
Output:
GfG! GfG! GfG!

 println(): This method in Java is also used to display a text on the console. It prints the text
on the console and the cursor moves to the start of the next line at the console. The next
printing takes place from the next line.

 Syntax:
System.out.println(parameter);
Example:
// Java code to illustrate println()

import java.io.*;
class Demo_print {
public static void main(String[] args)
{
// using println()
// all are printed in the
// different line
System.out.println("GfG! ");
System.out.println("GfG! ");
System.out.println("GfG! ");
}
}
Output:
GfG!
GfG!
GfG!
 printf(): This is the easiest of all methods as this is similar to printf in C. Note that
System.out.print() and System.out.println() take a single argument, but printf() may take
multiple arguments. This is used to format the output in Java.
Example:
// A Java program to demonstrate working of printf() in Java
class JavaFormatter1 {
public static void main(String args[])
{
int x = 100;
System.out.printf( "Printing simple" + " integer: x = %d\n", x);

// this will print it upto


// 2 decimal places
System.out.printf(
"Formatted with"
+ " precision: PI = %.2f\n",
Math.PI);

float n = 5.2f;

// automatically appends zero


// to the rightmost part of decimal
System.out.printf( "Formatted to " + "specific width: n = %.4f\n", n);

n = 2324435.3f;

// here number is formatted from


// right margin and occupies a
// width of 20 characters
System.out.printf(
"Formatted to "
+ "right margin: n = %20.4f\n",
n);
}
}
 Output:
 Printing simple integer: x = 100
 Formatted with precision: PI = 3.14
 Formatted to specific width: n = 5.2000
 Formatted to right margin: n = 2324435.2500
Using System.err.println()
By convention, this output stream is used to display error messages or other
information that should come to the immediate attention of a user even if the principal output
stream, the value of the variable out, has been redirected to a file or other destination that is
typically not continuously monitored.

Syntax

System.err.println("Got an error: " + e);

Types of Streams:
 Depending on the type of operations, streams can be divided into two primary classes:
1. Input Stream: These streams are used to read data that must be taken as an input from
a source array or file or any peripheral device. For eg., FileInputStream,
BufferedInputStream, ByteArrayInputStream etc.

2. Output Stream: These streams are used to write data as outputs into an array or file or
any output peripheral device. For eg., FileOutputStream, BufferedOutputStream,
ByteArrayOutputStream etc.
 Depending on the types of file, Streams can be divided into two primary classes which can
be further divided into other classes as can be seen through the diagram below followed
by the explanations.

1. ByteStream: This is used to process data byte by byte (8 bits). Though it has many
classes, the FileInputStream and the FileOutputStream are the most popular ones. The
FileInputStream is used to read from the source and FileOutputStream is used to write
to the destination. Here is the list of various ByteStream Classes:

2. CharacterStream: In Java, characters are stored using Unicode conventions (Refer this
for details). Character stream automatically allows us to read/write data character by
character. Though it has many classes, the FileReader and the FileWriter are the most
popular ones. FileReader and FileWriter are character streams used to read from the
source and write to the destination respectively. Here is the list of various
CharacterStream Classes:

1.2 Stream filter() in Java

Stream filter(Predicate predicate) returns a stream consisting of the elements of this


stream that match the given predicate. This is an intermediate operation. These operations
are always lazy i.e, executing an intermediate operation such as filter() does not actually
perform any filtering, but instead creates a new stream that, when traversed, contains the
elements of the initial stream that match the given predicate.
Syntax:
Stream<T> filter(Predicate<? super T> predicate)
Where Stream is an interface and T is the type of the input to the predicate.

Implementation:
1. Filtering out the elements divisible by some specific number ranging between 0 to 10.
2. Filtering out the elements with an upperCase letter at any specific index.
3. Filtering out the elements ending with custom alphabetical letters.

Example 1: filter() method with the operation of filtering out the elements with an upperCase
letter at index 1.

import java.util.stream.Stream;

// Class
class GFG {

// Main driver method


public static void main(String[] args)
{
// Creating a stream of strings
Stream<String> stream = Stream.of(
"Geeks", "fOr", "GEEKSQUIZ", "GeeksforGeeks");

// Getting a stream consisting of the


// elements having UpperCase Character
// at custom index say be it '1'
// using Stream filter(Predicate predicate)
stream
.filter(
str -> Character.isUpperCase(str.charAt(1)))
.forEach(System.out::println);
}
}
OutPut : fOr GEEKSQUIZ

1.2. 2 Stream pipelining

Stream pipelining is the concept of chaining operations together. This is done by


splitting the operations that can happen on a stream into two categories. They are
"intermediate operations" and "terminal operations". Each intermediate operation returns an
instance of Stream itself when it runs, an arbitrary number of intermediate operations can,
therefore, be set up to process data forming a processing pipeline. There must then be a
terminal operation which returns a final value and terminates the pipeline.

A PipedInputStream should be connected to a PipedOutputStream. The data written to


the PipedOutputStream by one thread, can thus be read from the
connected PipedInputStream by another thread

The following code Creates piped input and outpu t streams and connect them

Syntax

1.3 Byte Code in Java

Byte code is an intermediate code that is created by the compiler after compiling the user-
written code and we can run that intermediate code anywhere with the help of a Java Virtual
machine. Java bytecode is a low-level representation of Java code, consisting of a series of
instructions for the JVM to execute.

The main advantage of Java’s use of bytecode is that the JVM can optimize the code for the
specific machine it’s running on. This can result in improved performance compared to the
same code compiled directly to machine code. The JVM can also perform various checks and
optimizations during runtime, such as garbage collection, dynamic class loading, and security
checks.
Advantages of Byte Code in Java

 Portability: One of the biggest advantages of Java’s use of bytecode is that it


allows code to run on any platform that has a Java Virtual Machine (JVM)
installed.
 Performance optimization: The JVM can optimize the bytecode for the specific
machine it’s running on, resulting in improved performance compared to the
same code compiled directly to machine code.
 Reverse engineering prevention: Although bytecode can be decompiled back
into Java source code, it can be obfuscated to make it more difficult to
decompile. This makes it harder for attackers to reverse-engineer the code and
discover its inner workings.
 Cross-platform development: Java’s use of bytecode makes it easy for
developers to create cross-platform applications, as the same code can run on
different platforms without modification.

1.4 Reflection

Reflection is a feature in the Java programming language. It allows an executing Java


program to examine or "introspect" upon itself, and manipulate internal properties of the
program. For example, it's possible for a Java class to obtain the names of all its members and
display them Reflection can be used to get the information about :

1. Class : To know the name of the class to which that particular object belongs we can use
the getClass() method.

2. Constructors : To know the public constructors of the class to which that particular
object belongs we can use the getConstructors() method.

3. Methods : To know the public methods of the class to which that particular object
belongs we can use the getMethods() method.

Example

1. Using forName() method : This method is used to load the class dynamically and return
the instance of the Class class. The forName() method cannot be used for primitive
types.
class Animal { }
class Dog
{
public static void main ( String args[] )
{
Class a = Class.forName ( "Animal" );
System.out.println ( a.getName() );
}
} Output : Animal

Understanding Dynamic Class Loading:

Dynamic class loading in Java refers to the process of loading and using classes at runtime,
instead of loading them during the static compilation phase. By dynamically loading classes, Java
programs gain the ability to load and execute code on-demand, thereby enabling the creation of
more flexible and extensible applications.

Java provides a rich set of APIs and mechanisms to dynamically load classes, such as the
Class.forName() method, ClassLoader instances, and reflection.

try {
Class<?> dynamicClass = Class.forName("com.example.DynamicClass");

// Instantiate an object of the dynamically loaded class

Object dynamicObject = dynamicClass.newInstance();

// Invoke a method on the dynamically loaded object

dynamicClass.getMethod("someMethod").invoke(dynamicObject);
} catch (ClassNotFoundException | InstantiationException |
IllegalAccessException | NoSuchMethodException |
InvocationTargetException e) {
e.printStackTrace();
}
In the above example, we load the class com.example.DynamicClass dynamically at runtime
using Class.forName(). We then instantiate an object of the loaded class and invoke a method
called someMethod(). This allows us to execute code that was not known at compile-time,
bringing runtime flexibility to our Java application.

1.5 Java Threads

Threads allows a program to operate more efficiently by doing multiple things at the same
time.

Threads can be used to perform complicated tasks in the background without interrupting the
main program.

Typically, we can define threads as a subprocess with lightweight with the smallest unit of
processes and also has separate paths of execution. These threads use shared memory but
they act independently hence if there is an exception in threads that do not affect the
working of other threads despite them sharing the same memory.

The Concept Of Multitasking


To help users Operating System accommodates users the privilege of multitasking, where
users can perform multiple actions simultaneously on the machine. This Multitasking can be
enabled in two ways:
1. Process- Multitasking
2. Thread- Multitasking

1. Process-Based Multitasking (Multiprocessing)


In this type of Multitasking, processes are heavyweight and each process was allocated by a
separate memory area. And as the process is heavyweight the cost of communication
between processes is high and it takes a long time for switching between processes as it
involves actions such as loading, saving in registers, updating maps, lists, etc.
2. Thread-Based Multitasking
As we discussed above Threads are provided with lightweight nature and share the same
address space, and the cost of communication between threads is also low.
Life Cycle Of Thread
There are different states Thread transfers into during its lifetime, let us know about those
states in the following lines: in its lifetime, a thread undergoes the following states, namely:
 New State As we use the Thread class to construct a thread entity, the thread is born
and is defined as being in the New state. That is, when a thread is created, it enters a
new state, but the start() method on the instance has not yet been invoked.
 Runnable State A thread in the runnable state is prepared to execute the code. When a
new thread's start() function is called, it enters a runnable state.
 In the runnable environment, the thread is ready for execution and is awaiting the
processor's availability (CPU time). That is, the thread has entered the queue (line) of
threads waiting for execution.
 Running State Running implies that the processor (CPU) has assigned a time slot to the
thread for execution. When a thread from the runnable state is chosen for execution by
the thread scheduler, it joins the running state.
 In the running state, the processor allots time to the thread for execution and runs its
run procedure. This is the state in which the thread directly executes its operations.
Only from the runnable state will a thread enter the running state.
 Blocked State When the thread is alive, i.e., the thread class object persists, but it
cannot be selected for execution by the scheduler. It is now inactive.
 Dead State When a thread's run() function ends the execution of sentences, it
automatically dies or enters the dead state. That is, when a thread exits the run()
process, it is terminated or killed. When the stop() function is invoked, a thread will also
go dead.
Java Native Interface
The Java Native Interface (JNI) is a framework that allows your Java code to call native
applications and libraries written in languages such as C, C++ and Objective-C
In software design, the Java Native Interface (JNI) is a foreign function interface programming
framework that enables Java code running in a Java virtual machine (JVM) to call and be called
by native applications (programs specific to a hardware and operating system platform) and
libraries written in other languages .
Native methods are Java™ methods that start in a language other than Java. Native methods
can access system-specific functions and APIs that are not available directly in Java.

public class HelloJNI { // Save as HelloJNI.java


static {
System.loadLibrary("hello"); // Load native library hello.dll (Windows) or libhello.so (Unixes)
// at runtime
// This library contains a native method called sayHello()
}

// Declare an instance native method sayHello() which receives no parameter and returns void
private native void sayHello();

// Test Driver
public static void main(String[] args) {
new HelloJNI().sayHello(); // Create an instance and invoke the native method
}
}

Java Swing Tutorial

Java Swing tutorial is a part of Java Foundation Classes (JFC) that is used to create window-
based applications. It is built on the top of AWT (Abstract Windowing Toolkit) API and entirely
written in java.

Unlike AWT, Java Swing provides platform-independent and lightweight components.

The javax.swing package provides classes for java swing API such as JButton, JTextField,
JTextArea, JRadioButton, JCheckbox, JMenu, JColorChooser etc.
 Swing is a Set Of API ( API- Set Of Classes and Interfaces )
 Swing is Provided to Design Graphical User Interfaces
 Swing is an Extension library to the AWT (Abstract Window Toolkit)
 Includes New and improved Components that have been enhancing the looks and
Functionality of GUIs’
 Swing is more portable and more flexible than AWT, The Swing is built on top of the AWT
 Swing is Entirely written in Java
 Java Swing Components are Platform-independent And The Swing Components are
lightweight

Features Of Swing Class


Some of the notable features of Java Swing are:
 Platform Independence: Platform independence is one of Java Swing’s most remarkable
features. It can run on any platform that supports Java. Thus, Swing-based applications can
run on Windows, Mac, Linux, or any other Java-compatible operating system.
 Lightweight Components: Java Swing provides a set of lightweight components that are
easy to use and customizable. These components are designed to consume less memory
and use less processing power, making Swing-based applications run efficiently.
 Pluggable Look and Feel: Java Swing provides a pluggable look and feels that allows
developers to customize the appearance of the GUI according to the user’s preferences.
Developers can choose from several pre-built looks and feel themes or create their own
custom themes.
 Layout Managers: Java Swing provides a set of layout managers that can be used to
organize the graphical components in a GUI. These layout managers enable developers to
create flexible and responsive GUIs that adapt to different screen sizes and resolutions.
 Robust Event Handling Mechanism: Java Swing provides a robust event handling
mechanism that allows developers to handle events generated by the graphical
components. Developers can register event listeners to detect and respond to user
interactions with the GUI.
Example 1: Develop a program using label (swing) to display message “GFG WEB Site Click”
import java.io.*;
import javax.swing.*;

// Main class
class GFG {

// Main driver method


public static void main(String[] args)
{
JFrame frame
= new JFrame(); // creating instance of JFrame

JButton button = new JButton(


" GFG WebSite Click"); // creating instance of
// JButton
button.setBounds(
150, 200, 220,
50); // x axis, y axis, width, height

frame.add(button); // adding button in JFrame

frame.setSize(500, 600); // 400 width and 500 height


frame.setLayout(null); // using no layout managers
frame.setVisible(true); // making the frame visible
}
}

Output:

You might also like